c++ class variables and default construction -
class classb { int option; public: classb(void){} //without default constructor, example not compile. classb(int option) { this->option = option; } }; class classa { classb objb; //initialize objb using default constructor. when occur? public: classa(int option) { objb = classb(option); //initialize objb again using constructor. } }; int main(void) { classa obja (2); return 0; }
i'm new c++ (coming c#), , i'm bit confused how class variables initialized. in above example, classa declares class object of type classb, stored value. in order this, classb must have default constructor, implies classa first creates classb using default constructor. classa never uses default objb because it's overwritten in classa's constructor.
so question: objb initialized twice?
if so, isn't unnecessary step? faster declare objb pointer?
if not, why classb need have default constructor?
the reason not initializing objb
data member, assigning after has been default constructed.
classa(int option) { // time here, objb has been constructed // requires classb default constructable. objb = classb(option); // assignment, not initialization }
to initialize it, use constructor member initialization list:
classa(int option) : objb(option) {}
this initializes objb
right constructor, , not require classb
default constructable. note same applies classb
, constructors should be
classb() : option() {} // initializes option value 0 classb(int option) : option(option) {}
Comments
Post a Comment