views:

1393

answers:

3

I ran into a problem where after my class overrode a function of its base class, all of the overloaded versions of the functions were then hidden. Is this by design or am I just doing something wrong?

Ex.

class foo
{
  public:
    foo(void);
    ~foo(void);
    virtual void a(int);
    virtual void a(double);
};

class bar : public foo 
{
  public:
    bar(void);
    ~bar(void);
    void a(int);
};

the following would then give a compile error saying there is no a(double) function in bar.

main() 
{
  double i = 0.0;
  bar b;
  b.a(i);
}
+4  A: 
Thomas L Holaday
This is not true at all, you can very well override just one function.
Paolo Tedesco
My only defense is that I wrote a lot of C++ before 1996. Sigh.
Thomas L Holaday
Ah, the good old times :)
Paolo Tedesco
+20  A: 

In class bar, add

using foo::a;

This is a common 'gotcha' in C++. Once a name match is found in the a class scope, it doesn't look further up the inheritance tree for overloads. By specifying the 'using' declaration, you bring all of the overloads of 'a' from 'foo' into the scope of 'bar'. Then overloading works properly.

Keep in mind that if there is existing code using the 'foo' class, its meaning could be changed by the additional overloads. Or the additional overloads could introduce ambiguity and and the code will fail to compile. This is pointed out in James Hopkin's answer.

Fred Larson
Perfect explanation, thank you very much!
Greg
It is worth keeping in mind James Hopkin's point about valid code changing meaning when additional functions are added to a base class.
Thomas L Holaday
@Thomas: Edited to add that point. Thanks.
Fred Larson
+3  A: 

It is by design. Overload resolution is restricted to a single scope. It prevents some nasty cases of valid code changing meaning when additional functions are added to a base class or to namespace scope.

James Hopkin