Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a constructor from another constructor (do constructor chaining) in C++?

As a C# developer I'm used to running 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 fail.

like image 401
Stormenet Avatar asked Nov 21 '08 09:11

Stormenet


People also ask

Can we call constructor from another constructor?

The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.

Can we call a constructor from another constructor 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

C++11: Yes!

C++11 and onwards has this same feature (called delegating constructors).

The syntax is slightly different from C#:

class Foo { public:    Foo(char x, int y) {}   Foo(int y) : Foo('a', y) {} }; 

C++03: No

Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:

  1. You can combine two (or more) constructors via default parameters:

    class Foo { public:   Foo(char x, int y=0);  // combines two constructors (char) and (char, int)   // ... }; 
  2. Use an init method to share common code:

    class Foo { public:   Foo(char x);   Foo(char x, int y);   // ... private:   void init(char x, int y); };  Foo::Foo(char x) {   init(x, int(x) + 7);   // ... }  Foo::Foo(char x, int y) {   init(x, y);   // ... }  void Foo::init(char x, int y) {   // ... } 

See the C++FAQ entry for reference.

like image 157
JohnIdol Avatar answered Oct 14 '22 08:10

JohnIdol


Yes and No, depending on which version of C++.

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

This changed in C++11 (aka C++0x), which added support for the following syntax:
(example taken from Wikipedia)

class SomeType {   int number;   public:   SomeType(int newNumber) : number(newNumber) {}   SomeType() : SomeType(42) {} }; 
like image 35
Cyrille Ka Avatar answered Oct 14 '22 09:10

Cyrille Ka