Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Templated class hierarchy does not warn about duplicate member name

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading