Is there a way to generate a warning when a derived class member variable name shadows one of its parents class, e.g
class Mother
{
public:
Mother() : i(0
I actually saw code as follows which shows the necessity of the shadow warnings.
int val = 0;
if (flag == aval)
int val = firstval;
else if (flag == bval)
int val = secondval;
else if
.
.
.
switch (val)
{
// put cases here
}
I have also seen shadow warnings where the inside variable was meant to be local, have no effect on the outside variable, and the shadowed variable was not supposed to be referenced. Actually, it was easier to just change the name to prevent the warning.
This will not show a warning because this is allowed. It is possible because "at most one of the one of the names is actually defined in that scope; others would be merely visible in that scope. Name resolution rules determine which name is chosen, if there are multiple candidates...You really do not want to give a warning for every case where the compiler picks between alternatives." - @MSalters.
In my tests, gcc
7.4.0 indeed does not show a warning for this with -Wshadow
(nor with other -Wshadow*
flags, and current documentation does not tell about this possibility.
However clang
6.0.0 has the option -Wshadow-field
(included in -Wshadow-all
) which gives on your code:
main.cxx:43:7: warning: non-static data member 'i' of 'Child' shadows member inherited from type 'Mother' [-Wshadow-field]
int i; /* NOK Expecting warning : declaration of 'int Child::i' shadows 'int Mother::i' */
main.cxx:34:7: note: declared here