delegating constructor
C++11 extends the scope of constructor. Now constructor can call another constructor of same class. such constructors are called as “delegating constructors”, it delegates the request to another constructor.
Use Case:
We have common functionalities across two or more constructors.
Solution: We can add new function named as init() and we can keep these common functionalities in init() function and can call this from all constructors.
Solution After C++11: We can keep these common functionalities in one constructor and other constructors can call that constructor. Calling constructors are called as delegating constructor because they are delegating the request.
Objective/Purpose:
We can keep common functionalities in one constructor and reduce the writing affords and remove the duplicate code.
Note: Below example is meant only for explaining the above topic.
source code with example:
/* Program: Delegating Constructor Author: Alpha Master Date: 9 March 2021 */ //Header File #include<iostream> class test {}; class sample { int mIa; public: sample() //equivalent to init() function { test t; std::cout<<"test object creation"<<std::endl; } sample(int tmp): mIa(tmp) { sample(); } sample(double tmp) { mIa = tmp; sample(); } }; int main() { std::cout<<"Delegating Constructor"<<std::endl; sample(5); sample(5.5); return 0; }
Output:
Delegating Constructor test object creation test object creation