Search code examples
c++classinitialization

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


Solution

  • 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.