C++ calling base class constructors

后端 未结 6 1885
无人及你
无人及你 2020-12-08 00:23
#include 
#include  
using namespace std;

// Base class
class Shape 
{
   public:
      void setWidth(int w)
      {
         width =         


        
6条回答
  •  攒了一身酷
    2020-12-08 01:06

    Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

    When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

    class A {..}
    class B : A {...}
    class C : B {...}
    C c;
    

    When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

    To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

    Derived() : Base(5)
    {      
    }
    

    If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

提交回复
热议问题