How to forward an 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 the constructor from another constructor initialization list in C ++ / CLI, it is also possible to do this in C #.

Example:

ref class Foo { Foo() {} Foo(int i) : Foo() {} } 
+6
visual-c ++ c ++ - cli delegating-constructor
source share
4 answers

It is called the "delegating constructor." It is not yet available in this language. But there is an official proposal, you will find it in Appendix F.3.1 of the language specification . Given Microsoft's stance on C ++ / CLI, this is unlikely to be released any time soon.


UPDATE: delegating constructors had a life outside the sentences in this application, they were added to the standard C ++ 11 language specification. Microsoft is working on introducing C ++ 11 add-ons. Delegating constructors have finally done this for VS2013. And they also work in C ++ / CLI in this release.

+14
source share

You can do the following

 ref class A { public: A(int p) : p(p) { this->A::A(); } A() : p(1) {} int p; }; 

Invalid C ++ code, but VC will compile it :)

+1
source share

Just stumbled on the same issue. In my case, I am using VS2010.

It is clear that VS2010 will never be updated in order to fully implement C ++ 11, use VS2015 if you need better compliance with the standard (what I do when I can). But for some (old) projects, I still have to use VS2010.

An approach that works in many cases (for me) is to use a private function with all the common initialization code. Example:

 class A { private: void Inidialise() { /* common initialisation here */ } public: A() { Initialise(); /* specific initialisation for A() here */ } A(bool a) { Initialise(); /* specific initialisation for A(bool) here */ } A(int b) { Initialise(); /* specific initialisation for A(int) here */ } /* etcetera */ } 

It does not solve all the "problems" and does not prevent all cases of code duplication, but it is of great importance.

0
source share

When you said, “I know there is no way to do this in pure C ++,” you were wrong. This can be done in C ++. You can use the layout operator for this.

 class A { public: A(int p) : p(p) { new(this)A(); } A() : p(1) {} int p; }; 
-5
source share

All Articles