c++ - initialize multiple variables with constructor overloading -
c++ - initialize multiple variables with constructor overloading -
let's in class constructor overloaded. can multiple info members initialized single object using different constructors of same class?
eg :
class demo{ int size; double k; public: demo(int s){ size=s; } demo(double p){ k = size+p; } void show(){ cout<<size<<" "<<k<<"\n"; } }; int main(){ demo = demo(0); = 4.7; a.show(); homecoming 0; }
is possible?
no, 1 time object constructed, it's constructed.
let's go through code , see (assuming no optimizations, please note many modern compilers copy-elision in debug or -o0 modes):
demo(0);
the code demo(0)
calls demo(int s)
constructor. temporary rvalue created. have temporary object values:
size = 0 k = uninitialized
demo = demo(0);
demo a
created using implicit copy constructor.
we have demo
object named a
next values:
size = 0 k = uninitialized
a = 4.7;
because a
constructed, phone call implicit assignment-operator. default assignment-operator re-create values 1 object other object. means 4.7
needs converted demo
object first. possible because of demo(double p)
constructor.
so temporary demo
object created values:
size = uninitialized k = uninitialized + 4.7 = undefined
these values copied a
, both of a
's info members undefined.
possible solutions
songyuanyao's solution of using constructor multiple parameters 1 way of doing it.
using setters way.
either way, recommend having constructors provide default values data-members.
demo(int s) { size = s; k = 0.0; // or other suitable value }
here's how create setter.
void setk (double p) { k = size + p; }
you this:
int main () { demo (0) ; a.setk (4.7) ; a.show () ; homecoming 0 ; }
c++ constructor
Comments
Post a Comment