object - How to call a C++ class Constructor from another Constructor -
this question has answer here:
i'm trying create object in c++ requires multiple object constructors. foo() , foo(int) foo(int) calls foo(). simplified code written below:
#include <iostream> class foo{ private: int ix; public: void printx(string slabel){ cout << slabel << " : " << " foo::ix = " << foo::ix << endl; }; void setx(int ix){ foo::ix = ix; foo::printx("setx(void) method"); }; foo(){ foo::ix = 1; foo::printx("foo(void) constructor"); }; foo(int ix){ foo::setx(ix); foo::printx("foo(int) constructor"); foo::foo(); foo::printx("foo(int) constructor"); }; }; int main( int argc, char** argv ){ foo bar(2); return 0; } the output of is
setx(void) method : foo::ix = 2 foo(int) constructor : foo::ix = 2 foo(void) constructor : foo::ix = 1 foo(int) constructor : foo::ix = 2 as results indicate setx method works expected. foo::ix equal 2 inside , outside of scope of function.
however when calling foo(void) constructor within foo(int) constructor, foo::ix stays equal 1 within constructor. exits out method, reverts 2.
so question 2-fold:
- why c++ behave (a constructor cannot called within constructor without values assigned)?
- how can create multiple constructor signatures, without redundant duplicate code doing same thing?
any appreciated.
thanks
foo::foo(); in foo::foo(int) not invoking default constructor on current object expected. constructs temporary foo, has nothing current object.
you can use delegating constructor (since c++11) this:
foo(int ix) : foo() { // ... }; note foo::foo() invoked in advance of body of foo::foo(int) here.
an alternative avoid duplicated code use setx() common initialization method. (or make new 1 if not appropriate.)
foo() { setx(1); // ... }; foo(int ix) { setx(ix); // ... };
Comments
Post a Comment