|
||||
|
Section 10:
|
[10.3] Can one constructor of a class call another constructor of the same class to initialize the this object? Updated!
[Recently updated due to C++11 syntax. Click here to go to the next FAQ in the "chain" of recent changes]
Nope. Let's work an example. Suppose you want your constructor Foo::Foo(char) to call another constructor of the same class, say Foo::Foo(char,int), in order that Foo::Foo(char,int) would help initialize the this object. Unfortunately there's no way to do this in C++. Some people do it anyway. Unfortunately it doesn't do what they want. For example, the line Foo(x, 0); does not call Foo::Foo(char,int) on the this object. Instead it calls Foo::Foo(char,int) to initialize a temporary, local object (not this), then it immediately destructs that temporary when control flows over the ;.
class Foo {
public:
Foo(char x);
Foo(char x, int y);
...
};
Foo::Foo(char x)
{
...
Foo(x, 0); // this line does NOT help initialize the this object!!
...
}
You can sometimes combine two constructors via a default parameter:
class Foo {
public:
Foo(char x, int y=0); // this line combines the two constructors
...
};
If that doesn't work, e.g., if there isn't an appropriate default parameter
that combines the two constructors, sometimes you can share their common code
in a private init() member function:
class Foo {
public:
Foo(char x);
Foo(char x, int y);
...
private:
void init(char x, int y);
};
Foo::Foo(char x)
{
init(x, int(x) + 7);
...
}
Foo::Foo(char x, int y)
{
init(x, y);
...
}
void Foo::init(char x, int y)
{
...
}
BTW do NOT try to achieve this via placement
new. Some people think they can say new(this) Foo(x, int(x)+7)
within the body of Foo::Foo(char). However that is bad, bad, bad.
Please don't write me and tell me that it seems to work on your
particular version of your particular compiler; it's bad. Constructors do a
bunch of little magical things behind the scenes, but that bad technique steps
on those partially constructed bits. Just say no.
|
|||