[c++] C++ calling base class constructors

#include <iostream>
#include <stdio.h> 
using namespace std;

// Base class
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
      Shape()
      {
    printf("creating shape \n");
      }
      Shape(int h,int w)
      {
     height = h;
         width = w;
         printf("creatig shape with attributes\n");
      } 
   protected:
      int width;
      int height;
};

// Derived class
class Rectangle: public Shape
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
      Rectangle()
      {
     printf("creating rectangle \n");
      }
      Rectangle(int h,int w)
      {
     printf("creating rectangle with attributes \n");
     height = h;
         width = w;
      }
};

int main(void)
{
   Rectangle Rect;

   Rect.setWidth(5);
   Rect.setHeight(7);

   Rectangle *square = new Rectangle(5,5);
   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   return 0;
}

The output of the program is given below

creating shape 
creating rectangle 
creating shape 
creating rectangle with attributes 
Total area: 35

When constructing both the derived class objects I see that it is always the default constructor of the base class that is called first. Is there a reason for this? Is this the reason why languages like python insist on explicit calls of base class constructors rather than implicit calls like C++?

This question is related to c++ object inheritance

The answer is


In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.

According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.

In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.


When objects are constructed, it is always first construct base class subobject, therefore, base class constructor is called first, then call derived class constructors. The reason is that derived class objects contain subobjects inherited from base class. You always need to call the base class constructor to initialze base class subobjects. We usually call the base class constructor on derived class's member initialization list. If you do not call base class constructor explicitly, the compile will call the default constructor of base class to initialize base class subobject. However, implicit call on default constructor does not necessary work at all times (for example, if base class defines a constructor that could not be called without arguments).

When objects are out of scope, it will first call destructor of derived class,then call destructor of base class.


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.


Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.


The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.

Rectangle(int h,int w):
   Shape(h,w)
  {...}

Will call the other base class constructor.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to inheritance

How to extend / inherit components? Inheritance with base class constructor with parameters Class is not abstract and does not override abstract method Why not inherit from List<T>? Can an interface extend multiple interfaces in Java? How to call Base Class's __init__ method from the child class? How should I have explained the difference between an Interface and an Abstract class? JavaScript OOP in NodeJS: how? When do I have to use interfaces instead of abstract classes? C++ calling base class constructors