Call constructor from constructor in C++

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.

Answers


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) {}
};

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 this link for reference.


Need Your Help

regex not working in python

python regex

I am working on writing a regex for phonenumber. I have made a very basic regex for matching a phone number.

Paypal REST API - Is Access Token Reusable?

php rest paypal

According to paypal rest docs, for every transaction to paypal I need to submit an 'Authorization:Bearer' which is an access token that is generated from a previous request. I wasn't able to glean ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.