Search code examples
c++c++11member-initialization

Nested Class. error: expected parameter declarator - for inner class instance


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.


Solution

  • 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 (=).