Can I call a constructor from another constructor

2018-12-31 04:34发布

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.

15条回答
裙下三千臣
2楼-- · 2018-12-31 05:15

It is worth pointing out that you can call the constructor of a parent class in your constructor e.g.:

class A { /* ... */ };

class B : public A
{
    B() : A()
    {
        // ...
    }
};

But, no, you can't call another constructor of the same class.

查看更多
梦醉为红颜
3楼-- · 2018-12-31 05:16

In C++11, a constructor can call another constructor overload:

class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () : Foo(42) {} //New to C++11
};

Additionally, members can be initialized like this as well.

class Foo  {
     int d = 5;         
public:
    Foo  (int i) : d(i) {}
};

This should eliminate the need to create the initialization helper method. And it is still recommended not calling any virtual functions in the constructors or destructors to avoid using any members that might not be initialized.

查看更多
无色无味的生活
4楼-- · 2018-12-31 05:16

No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:

  • Overload the constructor, using different signatures
  • Use default values on arguments, to make a "simpler" version available

Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.

查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 05:23

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.

查看更多
公子世无双
6楼-- · 2018-12-31 05:24

No, you can't call one constructor from another in C++03 (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) {}
};
查看更多
伤终究还是伤i
7楼-- · 2018-12-31 05:25

Another option that has not been shown yet is to split your class into two, wrapping a lightweight interface class around your original class in order to achieve the effect you are looking for:

class Test_Base {
    public Test_Base() {
        DoSomething();
    }
};

class Test : public Test_Base {
    public Test() : Test_Base() {
    }

    public Test(int count) : Test_Base() {
        DoSomethingWithCount(count);
    }
};

This could get messy if you have many constructors that must call their "next level up" counterpart, but for a handful of constructors, it should be workable.

查看更多
登录 后发表回答