I am a newbie and I know this is a very basic concept and might be a duplicate too. Is it not true that once a constructor is called its corresponding destructor has to be called? [code run on Dev C++]
class Base
{
public:
Base() { cout<<"Base Constructor\n";}
int b;
~Base() {cout << "Base Destructor\n"; }
};
class Derived:public Base
{
public:
Derived() { cout<<"Derived Constructor\n";}
int a;
~Derived() { cout<< "Derived Destructor\n"; }
};
int main () {
Base* b = new Derived;
//Derived *b = new Derived;
delete b;
getch();
return 0;
}
GIVES OUTPUT
Base Constructor
Derived Constructor
Base Destructor
Derived classes do not inherit or overload constructors or destructors from their base classes, but they do call the constructor and destructor of base classes. Destructors can be declared with the keyword virtual .
A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
Destructors are called automatically when a variable goes out of scope. Because the base class destructor is inherited, and because the derived class object "is" a base class object, both the derived class destructor (even if it is the "default" destructor) and the base class destructor are called automatically.
Your code has undefined behavior. The base class's destructor must be virtual
for the following to have defined behavior.
Base* b = new Derived;
delete b;
From the C++ standard:
5.3.5 Delete
3 In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
So in your case, the static type is Base
, and the dynamic type is Derived
. So the Base
's destructor should be:
virtual ~Base() {cout << "Base Destructor\n"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With