As a C# developer I'm used to run through constructors:
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 fails.
It is worth pointing out that you can call the constructor of a parent class in your constructor e.g.:
But, no, you can't call another constructor of the same class.
In C++11, a constructor can call another constructor overload:
Additionally, members can be initialized like this as well.
This should eliminate the need to create the initialization helper method. And it is still recommended not calling any virtual functions in the constructors or destructors to avoid using any members that might not be initialized.
No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:
Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.
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.
No, you can't call one constructor from another in C++03 (called a delegating constructor).
This changed in C++11 (aka C++0x), which added support for the following syntax:
(example taken from Wikipedia)
Another option that has not been shown yet is to split your class into two, wrapping a lightweight interface class around your original class in order to achieve the effect you are looking for:
This could get messy if you have many constructors that must call their "next level up" counterpart, but for a handful of constructors, it should be workable.