With regards to the sample code below, why is the destructor for the base class called twice?
class Base {
public:
Base() {
std::cout << "Base::Base()" << std::endl;
}
~Base() {
std::cout << "Base::~Base()" << std::endl;
}
};
class Derived : public Base {
public:
Derived() {
std::cout << "Derived::Derived()" << std::endl;
}
~Derived() {
std::cout << "Derived::~Derived()" << std::endl;
}
};
int main() {
Base a = Derived();
return EXIT_SUCCESS;
}
Here is a sample of the output when the program is run:
Base::Base()
Derived::Derived()
Derived::~Derived()
Base::~Base()
Base::~Base()
What happens is called slicing. You initialize an object of type
Basewith an object of typeDerived. Since any object of typeDerivedhas also an object of typeBasecontained (called “base-class sub-object”), there will be twoBaseobjects and oneDerivedobject in existance throughout the program. The Derived object (and its base-class sub-object of typeBase) only exists for the time of initialization, while the remainingBaseobject exists until end ofmain.Since there are two Base objects and one Derived object, you will also see one more Base destructors run.