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

前端 未结 15 2323
暖寄归人
暖寄归人 2020-11-22 01:27

As a C# developer I\'m used to running through constructors:

class Test {
    public Test() {
        DoSomething();         


        
相关标签:
15条回答
  • 2020-11-22 01:54

    In Visual C++ you can also use this notation inside constructor: this->Classname::Classname(parameters of another constructor). See an example below:

    class Vertex
    {
     private:
      int x, y;
     public:
      Vertex(int xCoo, int yCoo): x(xCoo), y(yCoo) {}
      Vertex()
      {
       this->Vertex::Vertex(-1, -1);
      }
    };
    

    I don't know whether it works somewhere else, I only tested it in Visual C++ 2003 and 2008. You may also call several constructors this way, I suppose, just like in Java and C#.

    P.S.: Frankly, I was surprised that this was not mentioned earlier.

    0 讨论(0)
  • 2020-11-22 01:54

    When calling a constructor it actually allocates memory, either from the stack or from the heap. So calling a constructor in another constructor creates a local copy. So we are modifying another object, not the one we are focusing on.

    0 讨论(0)
  • 2020-11-22 01:55

    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.

    0 讨论(0)
提交回复
热议问题