
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
#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
- Related Articles
- What are the rules to create a constructor in java?
- How to call the constructor of a superclass from a constructor in java?
- What are the identity rules for regular expression?
- What are the basic rules for JavaScript parameters?
- What are the golden rules for handling your money?
- What are the basic scoping rules for python variables?
- What are the rules for naming classes in C#?
- What are the rules for the Subscriber interface in Java 9?
- What are the rules for the Subscription interface in Java 9?
- What are the rules for the Publisher interface in Java 9?
- What are the rules for writing the symbol of an element?
- What are the rules for a functional interface in Java?
- What are the basic rules for defining variables in C++?
- What are the rules for the body of lambda expression in Java?
- What are the scoping rules for lambda expressions in Java?\n

Advertisements