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.
Would be more easy to test, than decide :) Try this:
and compile it with 98 std: g++ main.cpp -std=c++98 -o test_1
you will see:
so :)
I would propose the use of a
private friend
method which implements the application logic of the constructor and is the called by the various constructors. Here is an example:Assume we have a class called
StreamArrayReader
with some private fields:And we want to define the two constructors:
Where the second one simply makes use of the first one (and of course we don't want to duplicate the implementation of the former). Ideally, one would like to do something like:
However, this is not allowed in C++. For that reason, we may define a private friend method as follows which implements what the first constructor is supposed to do:
Now this method (because it's a friend) has access to the private fields of
o
. Then, the first constructor becomes:Note that this does not create multiple copies for the newly created copies. The second one becomes:
That is, instead of having one constructor calling another, both call a private friend!
When calling a constructor it actually allocates memory, either from the stack or from the heap. So calling a constructor in another constructor creates a local copy. So we are modifying another object, not the one we are focusing on.
I believe you can call a constructor from a constructor. It will compile and run. I recently saw someone do this and it ran on both Windows and Linux.
It just doesn't do what you want. The inner constructor will construct a temporary local object which gets deleted once the outer constructor returns. They would have to be different constructors as well or you would create a recursive call.
Ref: https://isocpp.org/wiki/faq/ctors#init-methods
This approach may work for some kinds of classes (when the assignment operator behaves 'well'):
If you want to be evil, you can use the in-place "new" operator:
Seems to work for me.
edit
As @ElvedinHamzagic points out, if Foo contained an object which allocated memory, that object might not be freed. This complicates things further.
A more general example:
Looks a bit less elegant, for sure. @JohnIdol's solution is much better.