Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22042

Why does gcc warn when lambda parameter shadows private member of base class

$
0
0

When enabling -Wshadow during compilation, why does gcc warn when the name of a parameter of a lambda defined in a derived class "shadows" the name of a private member variable of its base class? Example:

#include <iostream>

class Base {
private:
    int data;
};

class Derived: public Base {
public:
    void test(int val) {
        auto lambda = [](const auto& data) {};
        lambda(val);
    }
};

When compiling, gcc - tested with version 9.2 - shows (https://gcc.godbolt.org/z/bRmUzz):

<source>: In lambda function:
<source>:11:36: error: declaration of 'data' shadows a member of 'Derived' [-Werror=shadow]
   11 |   auto lambda = [](const auto& data) {};
      |                                    ^
<source>:5:6: note: shadowed declaration is here
    5 |  int data;
      |      ^~~~

Why does this generate a shadow warning and how to prevent it, without disabling -Wshadow altogether? data is private in the base class! Declaring a member variable called data in the derived class does not lead to such a warning, as expected.


Viewing all articles
Browse latest Browse all 22042

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>