How can I call another constructor from one constructor in C++?

How can I call another constructor from one constructor in C++?

 2
c++
Author: Nicolas Chabanovsky, 2010-10-22

4 answers

Starting with C++11, you can call one constructor from another, this is called "delegating constructors"

struct X {
   X(int a, int b) { std::cout << a+b; }
   X(int b) : X(1, b) {}
   X() : X(20) {}
};

X x; // X::X() вызывает X::X(int), который вызывает X::X(int, int)

In this case, you cannot call the constructors of class members at the same time as calling another constructor, for example:

struct B {
  B() : x(1) {}
  B(int x_) : B(), x(x_) {} // ОШИБКА: нельзя одновременно вызвать B() и x()
  int x;
};

As soon as one of the constructors has been called, the object is considered fully constructed, so an exception from the calling constructor will cause the class destructor to be called:

struct C {
  C(const char*) { throw 1; }

  C() {}
  C(int) : C() { throw 1; }

  ~C() { std::cout << "~C\n"; }
};

int main() {
  try {
    C c(""); // ничего не будет напечатано, деструктор не будет вызван
  } catch (...) {}

  try {
    C c(1); // будет напечатано "~C"
  } catch (...) {}
}
 4
Author: Abyx, 2016-01-18 10:48:53

There is no way to do this in C++03.

 4
Author: Nicolas Chabanovsky, 2016-01-18 10:49:28

If you need to duplicate the code in different constructors of the same object , it is better to put it in a separate function that will do all the rough work. And call this function from the constructors.

 1
Author: gecube, 2011-06-12 10:32:38

And what exactly did the author of the question want?

  class c1
    {
    public:
        c1();
        c1(int i){printf("\nint ca()");}
        c1(float i,int c){printf("\nfloat ca()");}
    };

    class test
    {
    c1 c;
    public:

        test():c(10,4){printf("test\n");}
            ~test() {printf("\n~test!!!!");}
    };
    int main()
    {
        test a;

    }
 0
Author: konstantin, 2011-02-13 19:21:34