Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 519
micka190 Avatar asked Mar 29 '19 05:03

micka190


2 Answers

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.

like image 193
R Sahu Avatar answered Oct 20 '22 07:10

R Sahu


At this level, those warnings are about setting best practices. Ensuring that your member variable names aren't the same as function parameter variable names is a good practice as far as making your code more readable. While "this->size" does remove the ambiguity, it also means the when you search for uses of size in that function, you have to check which variable you're referring to. Making the names different removes the ambiguity 2 months from now when you're fixing a bug :) Recommended fixes include either changing member variables to having a prefix such as m_size, which also has the benefit of improving auto-complete/intellisense, or changing parameter name.

I will note that warnings as errors and W4 is something I strongly recommend adhering to. Good on you for taking care of your code :)

like image 44
EnigmaticBacon Avatar answered Oct 20 '22 08:10

EnigmaticBacon