patterncppCritical
Can I call a constructor from another constructor (do constructor chaining) in C++?
Viewed 0 times
constructorfromchainingcancallanother
Problem
As a C# developer I'm used to running through constructors:
Is there a way to do this in C++?
I tried calling the Class name and using the 'this' keyword, but both fail.
class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : this(count) {
DoSomethingWithName(name);
}
}
Is there a way to do this in C++?
I tried calling the Class name and using the 'this' keyword, but both fail.
Solution
C++11: Yes!
C++11 and onwards has this same feature (called delegating constructors).
The syntax is slightly different from C#:
C++03: No
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
-
You can combine two (or more) constructors via default parameters:
-
Use an init method to share common code:
See the C++FAQ entry for reference.
C++11 and onwards has this same feature (called delegating constructors).
The syntax is slightly different from C#:
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};C++03: No
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
-
You can combine two (or more) constructors via default parameters:
class Foo {
public:
Foo(char x, int y=0); // combines two constructors (char) and (char, int)
// ...
};-
Use an init method to share common code:
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)
{
// ...
}See the C++FAQ entry for reference.
Code Snippets
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};class Foo {
public:
Foo(char x, int y=0); // combines two constructors (char) and (char, int)
// ...
};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)
{
// ...
}Context
Stack Overflow Q#308276, score: 1555
Revisions (0)
No revisions yet.