Reputation: 1531
I have a class Foo
with the ONLY constructer Foo(int length)
. I also have a class ´Bar´ with the member Foo myFoo = myFoo(100)
how would I initialize that? I can only initialize it if it has no length parameter in Foo constructer.
Thanks in advance
Upvotes: 1
Views: 4691
Reputation: 19731
I'm not sure if I understood you correctly, but normally members are initialized in constructor initializer lists:
class Bar
{
public:
Bar();
private:
Foo myFoo;
};
Bar::Bar()
// The following initializes myFoo
: myFoo(100)
// constructor body
{
}
Note that if Bar
has several constructors, you have to initialize myFoo
in each of them.
C++11 added initialization directly in the member declaration, like this:
class Bar
{
Foo myFoo = Foo(100);
};
However your compiler might not support that yet, or only support it with special flags.
Upvotes: 1
Reputation: 81409
This questions has come many times. You use constructor initialization lists to do that:
class Bar
{
Bar() : myFoo( 100 ) {}
Foo myFoo;
};
Those initialization lists let you call constructors for base classes as well as for members, and is the intended way to initialize them.
Upvotes: 4