- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements