Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In Derived Constructor

In Derived Destructor

In Base Destructor

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading