I have the class as follows:
class A{
private:
int a;
int b;
int c;
public:
A(int a1){
a1 >= 0 ? a = a1 : a = -1;
}
A(int a1, int b1, int c1) : A{ a1 }, b{ b1 }, c{ c1 } {} //<---------- this line gives the error
};
but this gives me the error "A delegating constructor cannot have other mem-initializers".
I ended up fixing the code and making it:
class A{
private:
int a;
int b;
int c;
public:
A(int a1){
a1 >= 0 ? a = a1 : a = -1;
}
A(int a1, int b1, int c1) : A{ a1 } {
b = b1;
c = c1;
}
};
And the error went away. My question is, WHY does this make the error go away? Why does the previous method not work?
As stated by others in comments, the reason is that this is how the language specification is defined. That's why you can get a compiler error with a helpful message describing the cause of the problem.
From [class.base.init]:
Now, as for your delegating constructor, I propose that you currently have this backwards. The constructor
A(int)is in fact a short-hand for your otherwise complete versionA(int, int, int). It makes more sense to delegate in the other direction, assuming you don't have a very special reason to not initializebandcat all:Note also that you don't need to add random suffixes to your identifiers in an attempt to avoid name collisions. See the following:
From [class.base.init]:
In short,
a{a >= 0 ? a : -1}initializes the membera, and all theaidentifiers inside the initializer list refer to the function parametera.