I know that there is no way to do this in pure C++, but I was wondering if it is possible to call a constructor from another constructor's initialization list in C++/CLI, same way one can do it in C#.
Example:
ref class Foo {
Foo() {}
Foo(int i) : Foo() {}
}
We can call an overloaded constructor from another constructor using this keyword but the constructor must be belong to the same class, because this keyword is pointing the members of same class in which this is used. This type of calling the overloaded constructor also termed as Constructor Chaining.
Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.
In C++03, you can't call one constructor from another (called a delegating constructor).
To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.
It is called a "delegating constructor". It is not available in the language yet. But there's a formal proposal, you'll find it in annex F.3.1 of the language specification. Given Microsoft's stance towards C++/CLI, that is unlikely to see the light of day anytime soon.
UPDATE: delegating constructors did have a life beyond the proposal in that annex, they were added to the standard C++11 language specification. Microsoft has been working on getting the C++11 additions implemented. Delegating constructors finally made it for VS2013. And they also work in C++/CLI in that edition.
You can do following
ref class A
{
public:
A(int p) : p(p) { this->A::A(); }
A() : p(1) {}
int p;
};
It is not valid C++ code , but VC compiles it fine :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With