Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
What are the rules for calling the superclass constructor C++?
In C++, a superclass serves as a base/parent class. When we create a derived class (or child class) from a superclass, sometimes we have to call the constructor of the base class along with the constructor of the derived class. Unlike Java, there is no reference variable for the superclass. If the constructor is non-parameterized, then it will be called automatically with the derived class, otherwise, we have to put the superclass constructor in the initializer list of the derived class.
Constructor Without Arguments
It is a default constructor where no argument is passed to it. Here, we create a constructor of the same name as a class and create base and derived class print output text.
Example
Following is the basic program of default constructor in C++.
#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;
return 0;
}
The above code produces the following output:
Constructor of base class Constructor of derived class
Constructor with an Arguments
It is a parameterized constructor that takes arguments by initiating an object with specific values.
Example
In this example, we use the same program structure as the previous example, but this time we explicitly pass the value 50 to the base class constructor using an initializer list, and 100 is passed to the derived class constructor.
#include <iostream>
using namespace std;
class MyBaseClass {
public:
MyBaseClass(int x) {
cout << "Constructor of base class: " << x << endl;
}
};
//base constructor as initializer list
class MyDerivedClass : public MyBaseClass {
public:
MyDerivedClass(int y) : MyBaseClass(50) {
cout << "Constructor of derived class: " << y << endl;
}
};
int main() {
MyDerivedClass derived(100);
return 0;
}
The above code produces the following output:
Constructor of base class: 50 Constructor of derived class: 100
