# V703. It is suspicious that the 'foo' field in derived class overwrites field in base class.

The analyzer has detected that a descendant class contains a field whose type and name coincide with those of some field of the parent class. Such a declaration may be incorrect as the inheritance technology in itself implies inheriting all the parent class' fields by the descendant, while declaring in the latter a field with the same name only complicates the code and confuses programmers who will be maintaining the code in future.

For example, see the following incorrect code:

    class U {
    public:
      int x;
    };

    class V : public U {
    public:
      int x;  // <=
      int z;
    };

This code may be dangerous since there are two x variables in the V class: 'V::x' proper and 'U::x'. The possible consequences of this code are illustrated by the following sample:

    int main() {
      V vClass;
      vClass.x = 1;
      U *uClassPtr = &vClass;
      std::cout << uClassPtr->x << std::endl; // <=
      ....
    }

This code will cause outputting an uninitialized variable.

To fix the error, we just need to delete the variable declaration in the descendant class:

    class U {
      public:
      int x;
    };

    class V : public U {
      public:
      int z;
    };

There are a few arguable cases the analyzer doesn't consider incorrect:

- conflicting fields have different types;
- at least one of the conflicting fields is declared as static;
- the base class' field is declared as private;
- private inheritance is used;
- the field is expanded through define;
- the field has one of the special names like "reserved" (such names point out that the variable is actually used to reserve some part of the class structure in the memory for future use).

We recommend that you always do code refactoring for all the places triggering the V703 warning. Using variables with the same name both in the base and descendant classes is far not always an error. But such code is still very dangerous. Even if the program runs well now, it's very easy to make a mistake when modifying classes later.

This diagnostic is classified as:

CERT-DCL01-C

You can look at examples of errors detected by the V703 diagnostic.