What are the rules for calling the superclass constructor C++?


In C++, we can derive some classes. Sometimes we need to call the super class (Base class) constructor when calling the constructor of the derived class. Unlike Java there is no reference variable for super class. If the constructor is non-parameterized, then it will be called automatically with the derived class, otherwise we have to put the super class constructor in the initializer list of the derived class.

In this example at first we will see constructor with no argument.

Example

 Live Demo

#include <iostream>
using namespace std;
class MyBaseClass {
   public:
      MyBaseClass() {
         cout << "Constructor of base class" << endl;
      }
};
class MyDerivedClass : public MyBaseClass {
   public:
      MyDerivedClass() {
         cout << "Constructor of derived class" << endl;
      }
};
int main() {
   MyDerivedClass derived;
}

Output

Constructor of base class
Constructor of derived class

Now let us see constructor which can take parameter.

Example

 Live Demo

#include <iostream>
using namespace std;
class MyBaseClass {
   public:
   MyBaseClass(int x) {
      cout << "Constructor of base class: " << x << endl;
   }
};
class MyDerivedClass : public MyBaseClass { //base constructor as initializer list
   public:
      MyDerivedClass(int y) : MyBaseClass(50) {
         cout << "Constructor of derived class: " << y << endl;
      }
};
int main() {
   MyDerivedClass derived(100);
}

Output

Constructor of base class: 50
Constructor of derived class: 100

Updated on: 30-Jul-2019

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements