0
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?

Madison Brown
  • 331
  • 3
  • 10
  • If you never saw before member initialization it's obvious you didn't read any decent C++ book. This is one huge mistake you're going to make... approaching C++ by experimentation is a suicide (because sometimes it's just illogical and because of UB). Do yourself a favor and read a good book from cover to cover first (http://stackoverflow.com/q/388242/320726). Some of them are free PDF downloads. – 6502 Oct 06 '13 at 19:31

1 Answers1

3

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) {}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Ok true, but ClassA still ends up constructing two ClassB's: a default one, then a non-default one, right? – Madison Brown Oct 06 '13 at 19:30
  • @MadisonBrown No, as I said, there is no requirement that `ClassB` be default constructable anymore. Only one `ClassB` is instantiated. – juanchopanza Oct 06 '13 at 19:31