Constructor & Destructor Order
Construction order
- Base classes (in the order they're listed in the class declaration)
- Member variables (in the order they're declared, not the order in the initializer list)
- The derived constructor body
Destruction order — exactly reversed
- Derived destructor body
- Members (reverse declaration order)
- Base classes (reverse order)
Think of it like building a house: foundation (base) → walls (members) → furniture (body). Demolition goes the other way.
Why it matters
- In the derived constructor body, the base and members are ready to use
- In the base constructor, the derived part doesn't exist yet → virtual calls from a base constructor do not reach the derived override ⚠️
- In the destructor, the derived part is destroyed before the base destructor runs
Initializer list order trap ⚠️
class Range {
int size_;
int end_;
public:
Range(int start, int len) : end_(start + len), size_(end_ - start) {} // BUG
};
size_ is declared first, so it's initialized first — using end_ before it's set! -Wall warns: "will be initialized after". ✅ List initializers in declaration order.
Default base constructor
If you don't call a base constructor explicitly, the base's default constructor is used. If the base has none → compile error.
Copying and base classes
A derived copy constructor must copy the base part too: Derived(const Derived& o) : Base(o), .... (The compiler-generated one does this automatically.)
Example
#include <iostream>
#include <string>
struct Part {
std::string name;
explicit Part(std::string n) : name(std::move(n)) { std::cout << " + member " << name << '\n'; }
~Part() { std::cout << " - member " << name << '\n'; }
};
class Vehicle {
public:
Vehicle() { std::cout << " + Vehicle (base)\n"; describe(); }
virtual ~Vehicle() { std::cout << " - Vehicle (base)\n"; }
virtual void describe() const { std::cout << " describe(): Vehicle version\n"; }
};
class Bike : public Vehicle {
public:
Bike() : engine_("engine"), wheels_("wheels") { // listed in declaration order
std::cout << " + Bike body\n";
describe();
}
~Bike() override { std::cout << " - Bike body\n"; }
void describe() const override { std::cout << " describe(): Bike version\n"; }
private:
Part engine_; // declared first -> constructed first
Part wheels_;
};
int main() {
std::cout << "Building a Bike:\n";
{
Bike b;
std::cout << "Using the Bike...\n";
}
std::cout << "Bike destroyed.\n";
return 0;
}
/* Output:
Building a Bike:
+ Vehicle (base)
describe(): Vehicle version
+ member engine
+ member wheels
+ Bike body
describe(): Bike version
Using the Bike...
- Bike body
- member wheels
- member engine
- Vehicle (base)
Bike destroyed.
*/