Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a base class's constructor and destructor get called with the derived ones?

Tags:

c++

I have a class called MyBase which has a constructor and destructor:

class MyBase
{
public:
    MyBase(void);
    ~MyBase(void);
};

and I have a class called Banana, that extends MyBase like so:

class Banana:public MyBase
{
public:
    Banana(void);
    ~Banana(void);
};

Does the implementation of the new constructor and destructor in Banana override the MyBase ones, or do they still exist, and get called say before or after the Banana constructor / destructor executes?

Thanks, and my apologies if my question seems silly.

like image 365
josef.van.niekerk Avatar asked Oct 28 '09 22:10

josef.van.niekerk


People also ask

Does the derived class call the base class constructor?

For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.

Does base class destructor get called?

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.

Does derived destructor call base destructor?

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.

Is base class destructor called first?

The body of an object's destructor is executed, followed by the destructors of the object's data members (in reverse order of their appearance in the class definition), followed by the destructors of the object's base classes (in reverse order of their appearance in the class definition).


2 Answers

A Base constructor will always be called before the derived constructor. The Base destructor will be called after Dervided destructor.

You can specify on derived constructor which Base constructor you want, if not the default one will be executed.

If you define other constructors but not default and don't specify on Derived constructor which one to execute it'll try default which doesn't exist and will crash compilation.

The above happens because once you declare one constructor no default constructors are generated.

like image 182
Arkaitz Jimenez Avatar answered Oct 27 '22 02:10

Arkaitz Jimenez


Constructors cannot be overriden. You can't declare a base class constructor in a derived class. A class constructor has to call a constructor in base class (if one is not explicitly stated, the default constructor is called) prior to anything else.

To be able to clean up the derived class correctly, you should declare the base class destructor as virtual:

virtual ~MyBase() { ... }
like image 25
mmx Avatar answered Oct 27 '22 03:10

mmx