

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- What are the rules to create a constructor in java?
- What are the identity rules for regular expression?
- What are the rules for naming classes in C#?
- What are the golden rules for handling your money?
- What are the basic scoping rules for python variables?
- How to call the constructor of a superclass from a constructor in java?
- 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 basic rules for defining variables in C++?
- What are the scoping rules for lambda expressions in Java?
- What are the rules for a functional interface in Java?
- What are the rules for the body of lambda expression in Java?
- What are the rules of Attribute Generalization?
- What are the constructor references in Java?
Advertisements