Anas Jawad
Anas Jawad

Reputation: 55

Why isn't GCC's -Wshadow flag being raised for member variable shadowing in inheritance for this code?

I'm trying to understand member shadowing in inheritance.

Consider this code with inheritance where both classes have a public data member named x.

class A {
    public:
        int x;
};

class B : public A {
    public:
        int x; 
};

int main(void)
{
    B test;
    return 0;
}

When I compile this with : c++ -Wshadow file.cpp I don't get any warnings. This confuses me because my understanding is that shadowing occurs when an inner scope declares a name that's already declared in an outer scope.

In this case, B::x seems to be shadowing A::x, and the shadowing is real because to access A::x in B, I would need to use scope resolution: test.A::x

What am I missing about how -Wshadow works with inheritance? Is this not considered shadowing, or is there something special about member variables in inheritance?

Upvotes: 4

Views: 106

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122130

-Wshadow warns about local variables:

Warn whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C) or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum. If this warning is enabled, it includes also all instances of local shadowing. This means that -Wno-shadow=local and -Wno-shadow=compatible-local are ignored when -Wshadow is used. Same as -Wshadow=global.

For example:

class A {
    public:
        int x = 0;
};

class B : public A { 
    void foo() {
        int x;  // warning: declaration of 'x' shadows a member of 'B'
    }    
};

In your example x is not a local variable.

The documentation does not mention warning about member variables that shadow a member from a base.

There is no deeper reason to this other than this is how GCC implements the warning. Note that e.g., Clang does also not warn for my example (see here).

Upvotes: 7

Related Questions