Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward overloaded constructor call to another constructor in C++/CLI

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() {}
}
like image 884
Yuri Astrakhan Avatar asked Mar 01 '10 16:03

Yuri Astrakhan


People also ask

Can overloaded constructor call another constructor?

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.

How do you call a constructor from another constructor in the same class?

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.

Can copy constructor call another constructor?

In C++03, you can't call one constructor from another (called a delegating constructor).

How do I call a parameterized constructor from another class in C#?

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.


2 Answers

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.

like image 162
Hans Passant Avatar answered Sep 27 '22 16:09

Hans Passant


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 :)

like image 35
NN_ Avatar answered Sep 27 '22 18:09

NN_