1

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

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3
Bar::Bar() : myFoo(100) { // constructor code } 

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.