简体   繁体   中英

Constructors calling in c++ (inherited classes)

#include <iostream>

class A
{
public:
  A()  { std::cout << "A's constructor called\n"; }
};

class B
{
public:
  B()  { std::cout << "B's constructor called\n"; }
};

class C: public B, public A  // Note the order
{
public:
  C()  { std::cout << "C's constructor called\n"; }
};

int main()
{
    C c;
    return 0;
}

Why is the constructor of class A and B called, when a new instance of C is created?

Output is

B's constructor called
A's constructor called
C's constructor called

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 the 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.

Why wouldn't it be? A C contains parts that are a B and an A respectively, and those parts need to be constructed as well. The constructor is the feature that performs this role.

kanishk tanwar's answer has more detail, but I was writing this anyway, so here's a very whistle stop tour of why it's happening to answer your question:

In order to ensure an instance of a class is properly initialised, a constructor for the base types are always called. If you don't specify which constructor you want to call (syntax: C() : B(), A() for C 's constructor), the default constructor is used. As a derived class builds on a base class, the base classes have to be constructed first.

In your case you have specified contents to your default constructor, so that is the code that is run when you instantiate C .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM