I have the following code
#include <iostream>
using namespace std;
class B{
int i;
public:
B(){
cout << "Constructing B\n";
}
void print(){
cout << "Printing from B with size : "<<sizeof(*this)<<endl;
}
};
class D:public B{
int i;
public:
D(){
cout << "Constructing D\n";
}
void print(){
cout << "Printing from D with size : "<<sizeof(*this)<<endl;
}
};
int main(){
B b;
b.print();
D d;
d.print();
D* dp;
dp->print();
}
Which gives me following output:
Constructing B
Printing from B with size : 4
Constructing B
Constructing D
Printing from D with size : 8
Printing from D with size : 8
So is it true that while you create a pointer to derived class it doesn't create the instance of a base class first? I don't think its true though because the size of D class is the proof. But its not even calling the base class constructor. Can anyone explain this?
Right now your pointer isn't be initialized at all, so trying to use it gives undefined behavior. Try something like:
Or to do it better, something like:
...and the
unique_ptr
will automatically delete theD
when it goes out of scope.Note, however, that you've define
print
as a non-virtual function, so the function that's invoked will depend on the type of pointer (or reference) used, not the type of the object it refers to. In addition, you haven't defined a virtual dtor.Therefore, if you were to do something like:
...and when it went out of scope, it would be destroyed incorrectly so you'd get undefined behavior. To correct this, you want to change B to something like this:
When you do this, the answer is "yes"--when you create the derived object, it'll first invoke the ctor for the base class, then the ctor for the derived class. When the derived object is destroyed, that is reversed: first the dtor for the derived class will be invoked, then when it finishes the dtor for the base class will execute.