简体   繁体   中英

Initializing a member variable with parameters in c++

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

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.

Bar::Bar()
: myFoo(100) {

// constructor code

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM