C++ Constructors and Destructors — Complete Beginner Guide
Learning Objectives
- Write a constructor that sets starting state
- Overload constructors for flexible creation
- Use a member initialization list
- Explain when destructors run
Special Member Functions
A constructor is a special function that runs automatically when an object is created. It prepares valid starting values so you never use a half built object. A destructor runs automatically when the object's lifetime ends and cleans up.
Your First Constructor
The constructor shares the class name and has no return type.
#include <iostream>
#include <string>
class User {
public:
std::string name;
int level;
User(std::string n, int l) {
name = n;
level = l;
std::cout << "User created" << std::endl;
}
};
int main() {
User u("Ada", 1);
return 0;
}
Creating u immediately stores Ada and 1, then prints the creation message.
Default Constructor
A constructor with no required arguments is a default constructor. If you define any constructor yourself, the compiler no longer auto-generates one unless you ask for it.
class Sensor {
public:
double reading = 0.0;
Sensor() {
reading = 0.0;
}
};
Provide defaults or extra overloads so callers still have convenient creation paths.
Constructor Overloading
Multiple constructors let objects start from different information.
class Point {
public:
double x;
double y;
Point() : x(0.0), y(0.0) {}
Point(double xVal, double yVal) : x(xVal), y(yVal) {}
};
Callers can choose the origin form or the explicit coordinate form.
Member Initialization List
The colon syntax before the body assigns members before normal statements run. It is preferred for performance and for types without default construction.
class Player {
public:
std::string name;
int score;
Player(std::string n) : name(n), score(0) {}
};
| Body Assignment | Initialization List |
|---|---|
| Constructs then assigns | Constructs directly with value |
| Works for assignable members | Required for const and references |
| Slightly later setup | Clearer ordering intent |
Destructors in Action
A destructor has the class name prefixed with a tilde and takes no parameters.
class FileHandle {
public:
FileHandle() {
std::cout << "open" << std::endl;
}
~FileHandle() {
std::cout << "close" << std::endl;
}
};
When the object leaves its scope, the destructor body runs. Stack objects destroy in reverse creation order at the end of the block.
int main() {
FileHandle h; // prints open
return 0; // prints close before exit
}
Lifetime Timeline
| Event | What Runs |
|---|---|
| Creation | Constructor body after init list |
| During life | Member functions mutate state |
| Scope end or delete | Destructor runs once |
| After destruction | Storage is no longer valid |
You must not call member functions on an object after its destructor has finished.
When You Need Custom Logic
Default member cleanup often suffices because modern C plus plus types such as string and vector manage their own memory. Write a custom destructor when your class holds a raw resource: a file handle, network socket, or manual memory buffer.
class Buffer {
public:
Buffer(int n) : data(new int[n]), size(n) {}
~Buffer() {
delete[] data;
}
private:
int* data;
int size;
};
Later lessons cover smart pointers and RAII, which make this pattern safer and shorter.
Copy Surprises
If your destructor releases memory, default copying can lead to double frees. That is a deeper topic, but notice the rule of three early: if you define a destructor, destructor, copy constructor, and copy assignment often need review too.
For beginners, prefer letting standard library members manage resources until you intentionally design a resource class.
Common Mistakes
| Mistake | Result |
|---|---|
| Forgetting semicolon after class | Syntax error |
| Manual constructor call syntax confusion | Know how to pass arguments |
| Doing heavy work that can fail silently | Validate carefully later |
| Using object before constructor completes | Impossible by design, do not try |
| Destroying then reusing object | Undefined behavior |
A Complete Example
#include <iostream>
#include <string>
class Product {
public:
std::string title;
double price;
Product() : title("untitled"), price(0.0) {
std::cout << "default product" << std::endl;
}
Product(std::string t, double p) : title(t), price(p) {
std::cout << "product ready" << std::endl;
}
~Product() {
std::cout << "product gone" << std::endl;
}
void print() const {
std::cout << title << " costs " << price << std::endl;
}
};
int main() {
Product a;
Product b("Keyboard", 49.5);
b.print();
return 0;
}
Run it and match each printed line to creation or destruction events.
Key Takeaways
💡
- Constructors establish valid object state at creation
- Prefer member initialization lists for setup values
- Destructors run automatically at end of lifetime
- Defining any constructor removes the implicit default one
- Custom destructors are mainly for true external resources
Practice Questions
- Write a class Laptop with a constructor that sets brand and price.
- What happens to the implicit default constructor when you define another constructor?
- In what order do objects in one scope run their destructors?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions