c++ - How to initialize class members without using the copy constructor -
i'm writing c++ code maths. however, seems impossible use normal constructors initialize class members.
to instantiated, constructor of first called. time, p , q declaration p , q don't instantiated either. should able call constructor of b instantiate them. right? think maybe understanding of c++ classes wrong somewhere post here confirm.
class b{ // default constructor , copy constructor } class a{ private: b p; b q; public: explicit a(int _p, int _q); } // implementation a::a(int _p, int _q){ // computing goes here can't apply // a::a(int _p, int _q):p{_p}, q{_q} // p = b{_p} // q = b{_q} // works p{_p}; // can't compile. q{_q}; // what's wrong this? }
no, constructor's behavior looks this:
a::a(/* parameters */) : /* member constructors called here, explicitly or default, in order of declaration */ { /* constructor code */ }
in other words, time enter constructor's body, class members constructed, either initializer list if it's specified there, or default-constructed if not in initializer list. thus, a
constructor behaves if wrote a::a(int _p, int _q) : p{}, q{} { /* code */ }
. q = b{_q};
not call copy constructor; constructs temporary b
object , calls copy or move assignment operator of q
, since compiler generates in many cases, compiles. q{_q};
, statement, not valid c++.
Comments
Post a Comment