Introduction to the C++11 feature: delegating constructors
sumi_cj 270001SV2S Comment (1) Visits (82226)
In C++98, if a class has multiple constructors, these constructors usually perform identical initialization steps before executing individual operations. In the worst scenario, the identical initialization steps are copied and pasted in every constructor. See the following example:
These three constructors have the same function body. The duplicated codes make maintenance difficult. If you want to add more members or change the type of existing members, you have to make the same changes three times. To avoid code duplication, some programmers move the common initialization steps to a member function. The constructors achieve the same function by calling this member function. Let us revise the example as follows:
This revision eliminates code duplication but it brings the following new problems:
C++11 proposed a new feature called delegating constructors to solve this existing problem. You can concentrate common initialization steps in a constructor, known as the target constructor. Other constructors can call the target constructor to do the initialization. These constructors are called delegating constructors. Let us use this new feature for the program above:
You can see that delegating constructors make the program clear and simple. In this example, A() delegates to A(int i), so A(int i) is the target constructor of A(). A(int i) delegates to A(int i, int j), so A(int i, int j) is the target constructor of A(int i). Delegating and target constructors do not need special labels or disposals to be delegating or target constructors. They have the same interfaces as other constructors. As you haven seen from the example, a delegating constructor can be the target constructor of another delegating constructor, forming a delegating chain. Target constructors are chosen by overload resolution or template argument deduction. In the delegating process, delegating constructors get control back and do individual operations after their target constructors exit. See the following example:
Although we can use delegating chains in our program, we should avoid recursive calls of target constructors. For example:
In the preceding example, a recursive chain of delegation exists in the program. The program is ill-formed.
The output of the example is:
As described, the delegating constructors feature can be easily understood and used. This feature helps reduce the code size and make your program more readable and maintainable.