I've been pondering constructor delegation and how to efficiently without code duplication construct.
Let's consider the following
Code sample 101. Def cons is delegated to but delegating constructors must pass in dummy empty values. Problem is it is error prone and messy.
class A
{
int a1;
double a2;
string a3;
public:
A(int i=0, double d=0.0, string s="") : a1(i), a2(d), a3(s) {}
A(int i) : A(i) {}
A(double d) : A(0,d) {}
A(string s) : A(0,0.0,s) {}
}
Code sample 102 Much cleaner syntax, but not as efficient as 101. Delegating constructors re-assign value.
class A
{
int a1;
double a2;
string a3;
public:
A(int i=0, double d=0.0, string s="") : a1(i), a2(d), a3(s) {}
A(int i) : A() { a1=i; }
A(double d) : A() { a2=d;}
A(string s) : A() { a3=s;}
}
Code sample 103 No improvement over 102, in fact requires 1 extra constructor. So less code lean.
class A
{
int a1 = 0;
double a2 = 0.0;
string a3 = "";
public:
A() {}
A(int i) : A() { a1=i; }
A(double d) : A() { a2=d;}
A(string s) : A() { a3=s;}
A(int i, double d, string s) : a1(i), a2(d), a3(s) {}
}
Question: Is there a way to fix this code so that (1) there is little or no code repetition (2) Don't have to pass in dummy place holder values into constructor parameter (3) requires no re-assignment?
Aucun commentaire:
Enregistrer un commentaire