Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<iostream>
using namespace std;
 
class A
{
public:
  A()  { cout << "A's constructor called" << endl; }
};
 
class B
{
public:
  B()  { cout << "B's constructor called" << endl; }
};
 
class C: public B, public A  // Note the order
{
public:
  C()  { cout << "C's constructor called" << endl; }
};
 
int main()
{
    C c;
    return 0;
}


My question is why class B/A constructor is calling automatically when I make class c's object


output is
B's constructor called
A's constructor called
C's constructor called


What I have tried:

google.com and stackoverflow.com
Posted
Updated 17-Mar-18 0:07am
v2
Comments
KarstenK 17-Mar-18 14:15pm    
Avoid such heritance because it is defined in C++ in which order the constructors get called. So the solution 1 is is correct to some strange behavior.

1 solution

C is derived from both A and B - so before the constructor for C can be executed, the constructors for A and B must both be completed. If that wasn't the case, then teh C constructor could not rely on anything that its base classes provided.

For example, suppose A contained a list of items which is created and filed from a database in its constructor. All instances of A can rely on the list being complete because the constructor has to be finished before the instance is available to the rest of the code. But C is also an A - it derives from it in the same way that "a Ford" is also "A Car" - so it may well want to access that list. When you construct an instance, the base class constructors are automatically called before the derived classes to ensure that everything is ready for action when the derived constructor starts.

For example, change your code slightly:
class A
{
public:
A() { cout << "A's constructor called" << endl; }
};

class B: public A
{
public:
B() { cout << "B's constructor called" << endl; }
};

class C: public B
{
public:
C() { cout << "C's constructor called" << endl; }
};

int main()
{
C c;
return 0;
}
and you will get:
A's constructor called
B's constructor called
C's constructor called  
Because the base class constructors are all completed before the derived ones are executed.
 
Share this answer
 
Comments
Kala Lala 17-Mar-18 6:10am    
very nice explanation sir,thanks
OriginalGriff 17-Mar-18 6:23am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900