2

I have a C++ base class which declares a virtual method with two different signatures.

As soon as I override one of the virtual method signatures in a derived class the compiler (g++ 4.6.3 and g++ 4.7) is no longer able to match the method with the second signature in the same derived class.

The example code below will not compile if I only define SPECIALIZE_ONEARG to 1. In order to get it to compile again I also have to define PASSTHRU_TWOARG to 1. Using the "PASSTHRU" method isn't ideal because of efficiency and because the real class hierarchy is much deeper and I would prefer not to hardwire in the call to the base class.

Is this behavior specific to g++ or am I just trying to do something which isn't supported in C++?

#define SPECIALIZE_ONEARG ( 0 )
#define PASSTHRU_TWOARG   ( 0 )

class base
{
public:
  virtual int myMethod( char a )         { return 1; }
  virtual int myMethod( char a, int b )  { return 2; }
};

class derived : public base
{
public:
#if SPECIALIZE_ONEARG
  virtual int myMethod( char a )         { return 3; }
#endif // SPECIALIZE_ONEARG

#if PASSTHRU_TWOARG
  virtual int myMethod( char a, int b )  { return base::myMethod( a, b ); }
#endif // PASSTHRU_TWOARG
};

int main( int argc, char* argv[])
{
  derived myObj;

  return myObj.myMethod( 'a' ) * 10 + myObj.myMethod( 'b', 0 );
}
RonnieBr
  • 23
  • 1
  • 3

2 Answers2

7

Your definition is hiding the definition from the base class. In order for that definition to be visible at your derived scope, you need using base::myMethod.

class derived : public base
{
public:
  using base::myMethod; // <--- here

#if SPECIALIZE_ONEARG
  virtual int myMethod( char a )         { return 3; }
#endif // SPECIALIZE_ONEARG

#if PASSTHRU_TWOARG
  virtual int myMethod( char a, int b )  { return base::myMethod( a, b ); }
#endif // PASSTHRU_TWOARG
};
K-ballo
  • 80,396
  • 20
  • 159
  • 169
2

In the derived class, add

using base::myMethod;
NPE
  • 486,780
  • 108
  • 951
  • 1,012