2

I started learning about nested classes in C++, I tried a quick code which I pasted here to see how nested classes work. But the compilation end with some errors which I can't figure out.

File: check.cpp

class Outside{
    public:
        class Inside{
            private:
                int mInside;
            public:
                Inside(const int& x):mInside(x){}
        };
    private:
        Inside mOutside(20);
};

int main(void){
Outside o;
return 0;
}

The error which I get on compiling by g++ -Wall -std=c++11 -o check.out check.cpp

check.cpp:12:25: error: expected parameter declarator
        Inside mOutside(20);
                        ^
check.cpp:12:25: error: expected ')'
check.cpp:12:24: note: to match this '('
        Inside mOutside(20);
                       ^

I need a good explanation behind this error and how to overcome this error.

manlio
  • 18,345
  • 14
  • 76
  • 126
jblixr
  • 1,345
  • 13
  • 34

2 Answers2

7

You have to use = or {} for in-place member initialization:

// ...
private:
    Inside mOutside = 20;

The parentheses form would be ambiguous (it could be confused with a function declaration).


Inside mOutside{20};

With clang++ this triggers the warning:

warning: private field 'mInside' is not used [-Wunused-private-field]

and the compiler has a point. The strange thing is the missing warning with the other form (=).

manlio
  • 18,345
  • 14
  • 76
  • 126
1

Try using this way of member initializing.

Inside mOutside = Inside(20);

Yes, your solution worked thank you. But how? Why?

See Initializing bases and members in open-std.

Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34