Home > Net >  The constructor of base class is not called by derived class when base class pointer is used
The constructor of base class is not called by derived class when base class pointer is used

Time:01-08

Why the base class constructor is not called twice in the following code?

#include<iostream>
using namespace std;


class base{
    public:
        base(){cout << "In the Base Constructor\n"; }
         ~base(){
            cout << "In Base Destructor\n";
        }
};

class derived: public base{
    public:
        derived(){cout << "In Derived Constructor\n";}
        ~derived(){
            cout << "In Derived Destructor\n";
        }
};

int main(){
    base *bptr;
    derived d;
}

output:

In the Base Constructor

In Derived Constructor

In Derived Destructor

In Base Destructor

It must be because of the pointer. But I am not clear why?

CodePudding user response:

This is a pointer to something.

base *bptr;

It is not initialised.
It does not point to anything clean.
It especially does not point to any already created object.
Even if it did, that would not cause any constructor to be executed.
If there would be any object the pointer points to, then the creation of that object would have happened elsewhere, earlier.

This defines an object:

derived d;

This is what causes the observed execution of constructors.

  •  Tags:  
  • Related