Originally Posted by
grumpy
As laserlight asked, why not?
Your example seems rather silly - in fact, dangerous - because the member a is not actually initialised by the default constructor, but it is for an object constructed from an int - with no way for an object to detect the difference. Any member that retrieves the value of an uninitialised "a" will give undefined behaviour.
The solution to use common code in constructors - assuming that is OK from the constructor body - is typically to have a private initialiser function, and call it from each constructor.
You are absolutely correct about my example. In my code, which i was too lazy to type in here, it is a little bit different. Let me give you a better example.
I have a whole bunch of variables which are initialized to the same values in all specialized constructors and only one or two which are initialized to special values in each constructor respectively.
Code:
class Foo
{
public:
Foo(A a) : m1(0), m2(0), m3(0), a(a), b(NULL) {};
Foo(B b) : m1(0), m2(0), m3(0), b(b), a(NULL) {};
~Foo() {};
private:
int m1, m2, m3;
A a;
B b;
};
What i want to do is still the same, have a constructor with no arguments that initializes m1, m2 and m3 which can be called from the initialization list in each of the specialized constructors.
Code:
Foo(void) : m1(0), m2(0), m3(0) {};
Foo(A a) : Foo(), a(a), b(NULL) {};
Which would be much cleaner code.
Best regards, threahdead