C++ Constructor -
C++ Constructor -
possible duplicate: what weird colon-member syntax in constructor?
if define class shown below in c++:
class myclass { public: myclass (unsigned int param) : param_ (param) { } unsigned int param () const { homecoming param_; } private: unsigned int param_; };
what constructor definition: myclass (unsigned int param) : param_ (param)
means , benefit code?
myclass (unsigned int param) : param_ (param)
this build called member initializer list in c++.
it initializes fellow member param_
value param
.
what difference between initializing , assignment within constructor? & advantage?
there difference between initializing fellow member using initializer list , assigning value within constructor body.
when initialize fields via initializer list constructors called once.
if utilize assignment fields first initialized default constructors , reassigned (via assignment operator) actual values.
as see there additional overhead of creation & assignment in latter, might considerable user defined classes.
for integer info type(for utilize it) or pod class members there no practical overhead.
when have to
utilize fellow member initializer list? have(rather forced) utilize fellow member initializer list if:
your class has reference member class has const fellow member or class doesn't have default constructor
a code illustration depict have to
cases:
class myclass { public: int &i; //reference member, has initialized in fellow member initializer list int j; const int k; //const member, has initialized in fellow member initializer list myclass(int a, int b, int c):i(a),j(b),k(c) { } }; class myclass2:public myclass { public: int p; int q; myclass2(int x,int y,int z,int l,int m):myclass(x,y,z),p(l),q(m) { } }; int main() { int x = 10; int y = 20; int z = 30; myclass obj(x,y,z); int l = 40; int m = 50; myclass2 obj2(x,y,z,l,m); homecoming 0; }
myclass2
doesn't have default constructor has initialized through fellow member initializer list.
c++
Comments
Post a Comment