PRASANNAGANAPATHI S S
PRASANNAGANAPATHI S S

Reputation: 11

If we create a derived object, is the parent object also automatically created?

If I create derived object it calls base constructor first and then derived constructor. Does it mean that parent object also get created when we create derive object?

I don't think parent object gets created, but why does the parent constructor get called?

#include<iostream>
using namespace std;
 class A {
      public :  A(){ 
                  cout<<"inside A constructor"<<endl;
       }
    };
   class B : public A{
                  public : B(){
                            cout << "inside B constructor" << endl;
                          }
        };
    int main() {
                B b; 
               return 0;
            } 

Output:

inside A constructor
inside B constructor

Upvotes: 0

Views: 63

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122460

I don't think parent object get created [...]

You are wrong.

B constists of a A subobject and any members that B has in addition. Consider this example:

struct A {
    int a = 0;
};

struct B : A {
    B() {}
};

int main() {
    B b;
    b.a = 42;
}

B inherits the members from A. Those members do not come out of nowhere, but they are part of Bs subobject of type A and that has to be constructed. When you do not call a constructor explicitly then it will be default constructed. The above is roughly equivalent to:

struct A {
    int a = 0;
};

struct B : A {
    B() : A() {}
       // ^^^ call default constructor of A
};

Upvotes: 2

Related Questions