I have been refactoring, moving members from children classes to a common parent.
I’d like to use compiler warnings/errors to protect against the same variable appearing in child and parent (if I forgot to remove from a child).
The below produces a warning with Clang 16/17:
struct P
{
int a;
};
struct C : public P
{
int a;
};
int main()
{
return 0;
}
.
warning: non-static data member 'a' of 'C' shadows member inherited from type 'P' [-Wshadow-field]
However, in my situation I had a templated hierarchy:
template<class E>
struct P
{
int a;
};
template<class E>
struct C : public P<E>
{
int a;
};
int main()
{
C<double> c;
return 0;
}
and this does not produce a warning. Why is this?
>Solution :
This is a consequence of dependent names and template specialization. When you do
template<class E>
struct C : public P<E>
{
int a;
};
all you can really do is check that it is syntactically correct. We don’t know what E is yet so we can’t know what P<E> will turn into. There could be a specialization introduced after C that specializes P for double that has no members so there would be no member hiding.