1

Consider the following code.

class Base1
{
public:
  void func1(float x)
  {var1 = x;}

private:
  float var1;
};


class Derived1: public Base1
{
public:
  void func1(int x)
  {var1 = x;}

private:
  int var1;
};

Is it a good idea to redefine the variable var1 with a new data type (integer in this example)? Is there any problem with this? (e.g.: shadowing!)

Soo
  • 885
  • 7
  • 26
  • Probably not a good idea, but not harmful here either. – AndyG Dec 29 '16 at 20:12
  • you can make `int var1` in `protected` section of `Base1` class, then it will be accessible from `Derived1` – paweldac Dec 29 '16 at 20:17
  • the base field in your example is private anyway... – W.F. Dec 29 '16 at 20:17
  • Hiding is not overriding. The variable that `var1` refers to will depend on the context in which it is used. In method overriding, the method of the derived class will always be the one used unless explicitly qualifying it with `Base::` – A.S.H Dec 29 '16 at 20:18
  • Since it's a private variable, it's not visible in the derived class. As far as the derived class design is concerned, it might as well not exist. There's no relationship between the private member variables in the two classes. – Barmar Dec 29 '16 at 21:13
  • what is the aim of inheritance? – Raindrop7 Dec 29 '16 at 21:39

1 Answers1

2

Generally speaking, replacing the parent's variable with a new one with the same name, could be confusing and error prone.

In your example not only the variable is replaced, but also the function that sets it, by "Name Hiding" (you are referring to it as "Shadowing").

It seems you dislike a parent's attribute (and probably behavior) and that might be a signal that your class hierarchy should be revisited.

You can read about the "Name Hiding" rationale as a language feature here.

Community
  • 1
  • 1
GeorgeT
  • 484
  • 3
  • 5
  • Thanks for the answer. But the variable in the base class is purposefully chosen as "private" so that the variable will not be accessible in the Derived class. Hence I thought, it should not create any confusion in the Derived class. – Soo Dec 30 '16 at 05:02