Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can constructor call another constructor in c++?

class A{   A(int a = 5){     DoSomething();     A();   }   A(){...} } 

Can the first constructor call the second one?

like image 812
MainID Avatar asked Dec 13 '09 12:12

MainID


People also ask

Can a constructor call 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 constructors call each other?

To call one constructor from another constructor is called constructor chaining in java. This process can be implemented in two ways: Using this() keyword to call the current class constructor within the “same class”. Using super() keyword to call the superclass constructor from the “base class”.

Can a constructor call 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.

How would you call a constructor from another constructor in the same C?

They would have to be different constructors as well or you would create a recursive call. This is not "calling a constructor". The only place you can "call a constructor" directly is in the ctor-initializer in C++11.


2 Answers

Not before C++11.

Extract the common functionality into a separate function instead. I usually name this function construct().

The "so-called" second call would compile, but has a different meaning in C++: it would construct a new object, a temporary, which will then be instantly deleted at the end of the statement. So, no.

A destructor, however, can be called without a problem.

like image 151
Pavel Radzivilovsky Avatar answered Sep 24 '22 08:09

Pavel Radzivilovsky


Not before C++0x, no.

BUT, just out of academic interest I've come up with a really horrible way* to do it using a placement operator "new" (someone care to point out how portable this is?)

#include <new> #include <iostream>  class A { public:     A(int i, int j)         : i_(i), j_(j) { }      A(int i)     { new (this) A(i, 13); }      int i_,j_; };  int main() {     A a1(10,11), a2(10);     std::cout         << a1.i_ << ", "         << a1.j_ << std::endl         << a2.i_ << ", "         << a2.j_ << std::endl;     return 0; } 

*Hell no, I don't write this in the production code.

like image 28
Alex B Avatar answered Sep 23 '22 08:09

Alex B