Reputation: 331
class ClassB
{
int option;
public:
ClassB(void){} //without the default constructor, the example does not compile.
ClassB(int option)
{
this->option = option;
}
};
class ClassA
{
ClassB objB; //initialize objB using default constructor. When does this actually occur?
public:
ClassA(int option)
{
objB = ClassB(option); //initialize objB again using another constructor.
}
};
int main(void)
{
ClassA objA (2);
return 0;
}
I'm new to c++ (coming from c#), and i'm a bit confused about how class variables are initialized. In the above example, ClassA declares a class object of type ClassB, stored by value. In order to do this, ClassB must have a default constructor, which implies that ClassA first creates a ClassB using the default constructor. But ClassA never uses this default objB because it's immediately overwritten in ClassA's constructor.
So my question: Is objB actually initialized twice?
If so, isn't that an unnecessary step? Would it be faster to declare objB as a pointer?
If not, why does ClassB need to have a default constructor?
Upvotes: 0
Views: 222
Reputation: 227418
The reason for this is that you are not initializing the objB
data member, but assigning to it after it has been default constructed.
ClassA(int option)
{
// By the time you get here, objB has already been constructed
// This requires that ClassB be default constructable.
objB = ClassB(option); // this is an assignment, not an initialization
}
To initialize it, use the constructor member initialization list:
ClassA(int option) : objB(option) {}
This initializes objB
with the right constructor, and does not require ClassB
to be default constructable. Note that the same applies to ClassB
, whose constructors should be
ClassB() : option() {} // initializes option with value 0
ClassB(int option) : option(option) {}
Upvotes: 3