C++: Declaration of parameter hides class member even with "this" keyword

micka190 picture micka190 · Mar 29, 2019 · Viewed 7k times · Source

I've recently started using "Warning Level 4" and treating warnings as errors when coding in C++. I'd like some more in-depth information about the following snippet:

struct Foo
{
    Foo(int size)
        //:size{ size } // <- More on this later.
    {
        this->size = size;
    }

    void func(int size)
    {
        this->size = size;
    }

    int size;
};

int main()
{
    Foo a{ 1 };
    a.func(2);
}

So, I'm getting the following warning/error from Visual Studio 2019:

Error: C2220 - Warning treated as error - no 'object' file generated.

Warning: C4458 - Declaration of 'size' hides class member.

The warning indicates that the size member is being hidden by a method's parameter that is also named size. The output indicates that the error does not come from the constructor, but from the func method. I find this confusing, since the constructor doesn't seem to have this issue (indeed, removing func allows the snippet to compile).

Lowering the warning level allows the application to compile, and it seems to work as intended. Using the initializer list instead of the constructor's body (see commented line) also seems to work, but I'm guessing that's due to initializer list semantics.

I understand that the error says that the size parameter name of func conflicts with Foo's member of the same name, but shouldn't the this keyword fix that confusion? Is this just Microsoft's compiler being overly strict?

Answer

R Sahu picture R Sahu · Mar 29, 2019

but shouldn't the this keyword fix that confusion?

It's not that the compiler is confused about this->size being different than size. You will most likely get the warning even if you remove that line. The compiler is warning you about the fact that the argument name of the function hides the member name.