Delegating Constructor
What is delegating constructor?
Definition:one ctor can call another ctor
- 被构造函数放到主调构造函数初始化列表的位置
- 调用次序:A() → A(int) → A(int, int)
class A{
public:
A(): A(0){}
A(int i): A(i, 0){}
A(int i, int j) {
num1=i;
num2=j;
average=(num1+num2)/2;
}
private:
int num1;
int num2;
int average;
};
Avoiding recursive calls of target constructors
- 递归调用:函数调用其本身
- 调用次序(调用环):A() → A(int) → A(int, int) → A()
class A{
public:
A(): A(0){}
A(int i): A(i, 0){}
A(int i, int j): A(){}
private:
int num1;
int num2;
int average;
};
Adavantages
- Less code
- More clear code logic