alternatives to name hiding inherited non virtual functions

54 views Asked by At
struct Base
{
  int x;
  int foo() const
  {
    return x;
  }
};

struct Derived : Base
{
  int y;
  int foo() const
  {
    return Base::foo() + y;
  }
};

int main(int argc, char **argv) {
  Derived d;
  d.x = 1;
  d.y = 2;
  const Base& b = d;
  std::cout << b.foo() << std::endl;
  std::cout << d.foo() << std::endl;
  return 0;
}

I have this design issue. Two simple structs that are used to wrap some members which are accessed directly in parts of the code (The base has more members than shown). There is a function in the base class that aggregates these members together. The derived class defines some more members and the function aggregates those members to the result of the aggregation of the base. The aggregation function is called in a big loop, hence virtual function are not desired and that creates the problem shown in the main, the same object behaves differently when foo is called (because different function is called on the same object base vs derived version). I've considered some alternatives like using private inheritance which would have been approporiate if the members were not directly accesses in the code. Are there other alternatives to solving this problem, are there other problems with the name hiding other the one described above?

0

There are 0 answers