

- 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
Constructor Delegation in C++
Here we will see what is the constructor delegation? When a constructor calls other constructor of the same class, then it is called the constructor delegation. This feature is present from C++11.
Let us see the following program, and try to analyze what are the difficulties in this code.
Example
#include <iostream> using namespace std; class MyClass { int a, b, c; public: MyClass(){ a = b = c = 0; } MyClass(int c) { // Initializing a and b are redundent, only c initialization is needed here a = 0; b = 0; this->c = c; } void display(){ cout << "a : " << a << ", b : " << b << ", c : " << c; } }; main() { MyClass my_obj(5); my_obj.display(); }
Output
a : 0, b : 0, c : 5
Here we can see that the code is working fine, but there is some redundant code. The non-parameterized constructor can set the values of a and b to 1. So if we use the first constructor into the second one, then it will be more effective. For this reason, we have to use the method called constructor delegation.
Example
#include <iostream> using namespace std; class MyClass { int a, b, c; public: MyClass(){ a = b = c = 0; } MyClass(int c) : MyClass(){ //using constructor delegation this->c = c; } void display(){ cout << "a : " << a << ", b : " << b << ", c : " << c; } }; main() { MyClass my_obj(5); my_obj.display(); }
Output
a : 0, b : 0, c : 5
- Related Questions & Answers
- Delegation vs Inheritance in C#
- Generator delegation in PHP 7
- Difference between Static Constructor and Instance Constructor in C#
- Constructor overloading in Java
- Default constructor in Java
- Constructor Overloading in C#
- Default constructor in C#
- Copy Constructor in C++
- Enum constructor in Java
- Conversion constructor in C++?
- Virtual Constructor in C++
- Constructor Overloading in C++
- Java default constructor
- Java parameterized constructor
- Java copy constructor
Advertisements