Constructors and Destructors
A constructor initialises an object when it is created; a destructor cleans it up when it goes out of scope or is deleted. Together they manage an object's full lifecycle.
Constructors
A constructor shares the class's name and has no return type. It runs automatically whenever an object is created, and is the ideal place to guarantee an object always starts in a valid state.
class Account {
public:
std::string owner;
double balance;
// Constructor
Account(std::string ownerName, double startingBalance) {
owner = ownerName;
balance = startingBalance;
}
};
int main() {
Account acc("Lerato", 500.00); // constructor runs automatically
std::cout << acc.owner << ": R" << acc.balance << std::endl;
return 0;
}
Destructors
A destructor is prefixed with a tilde (~) and takes no parameters. It runs automatically when an object's lifetime ends, and is commonly used to release resources such as dynamically allocated memory or open files.
class Logger {
public:
Logger() { std::cout << "Logger started" << std::endl; }
~Logger() { std::cout << "Logger shutting down" << std::endl; }
};
Common Mistakes
- Giving a constructor a return type — constructors must never declare one, not even
void. - Forgetting that a class can have multiple overloaded constructors that accept different parameter lists.
- Assuming the destructor must be called manually — it runs automatically when an object leaves scope.
- Not initialising all member variables in a constructor, leaving some with unpredictable starting values.
Professional Tip
Prefer member initialiser lists over assignment inside the constructor body, e.g. Account(std::string n, double b) : owner(n), balance(b) {}. This is more efficient and is required for initialising const members and references.
Your Turn
Add a second, overloaded constructor to the Account class that takes only an owner name and sets the starting balance to 0 automatically. Create objects using both constructors.
Mini Quiz
What symbol is used to prefix a destructor's name in C++?
~ClassName(). The tilde distinguishes it from the constructor, which shares the same name without a prefix.