class A{ A(int a = 5){ DoSomething(); A(); } A(){...} }
Can the first constructor call the second one?
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.
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”.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With