C++ – construction of an object inside a class

c++constructoroop

I'm fairly new to C++, and I'm not sure about this one. Have a look at the following example which sums up my current problem.

class Foo
{
    //stuff
};

class Bar
{
    Foo foo;
};

So Bar constains a full Foo object, not just a reference or pointer. Is this object initialized by its default constructor ? Do I need to explicitly call its constructor, and if so, how and where ?

Thanks.

Best Solution

It will be initialized by its default constructor. If you want to use a different constructor, you might have something like this:

class Foo
{
    public: 
    Foo(int val) { }
    //stuff
};

class Bar
{
    public:
    Bar() : foo(2) { }

    Foo foo;
};