4

I have the following code (header file):

class InnerClass
{
    InnerClass(int var);
}

class BigClass
{
    BigClass();
    InnerClass member(5);
}

How can I initialize the parameter of member in BigClass to 5 (the above code generates an error, as you probably guessed)? If I put the InnerClass member(5) line in the code (not header) file, then no problem.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
dumbprog
  • 43
  • 4
  • Possible duplicate of [Why C++11 in-class initializer cannot use parentheses?](http://stackoverflow.com/questions/24836526/why-c11-in-class-initializer-cannot-use-parentheses) – cpplearner Mar 23 '16 at 10:05
  • Yes @cpplearner, part of this link answers my question. But I believe my question (and the accepted answer) is more direct to the point. Also the accepted answer clearly shows the difference with C++11 syntax. – dumbprog Mar 23 '16 at 10:35

1 Answers1

4

You could initialize the member variable BigClass::member by in-class brace-or-equal initializer (since c++11):

InnerClass member{5};

or member initializer list:

class BigClass
{
    InnerClass member;
public:
    BigClass() : member(5) {}
    // or... BigClass(int var) : member(var) {}
}

BTW: I suppose the constructor of InnerClass should be public.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405