penelope
penelope

Reputation: 8418

Overloading Base class method with extra default parameter in Derived

My base class offers a virtual method with no arguments, like this:

class Base{
   virtual void myMethod(void) = 0;
};

I would like to override it in the Derived class and offer an implementation (the Derived class is not supposed to be an abstract type), and additionally provide an optional parameter via setting the default value, as so:

class Derived : public Base{
   void myMethod(Thing *optional = NULL) { ... }
};

But I seem to be getting the error of the type:

error: cannot allocate an object of abstract type 'Derived'
   because the following virtual functions are pure within 'Derived':
   virtual void myMethod()

Now, I know that when overloading functions, the following functions can not exist along each other:

void myFunction();
void myFunction(Thing *optional = NULL);

because the function call myFunction() would match both declared functions. Following this logic, my definition in Derived should override the Base method with no arguments, and "add another method" with one argument, but it doesn't.

I know I can solve this problem by definitions like this:

class Derived : public Base{
    void myMethod(Thing *optional) { ... }
    void myMethod() { myMethod(NULL); }
};

My question is: is this really the only way to achieve the desired functionality? If so, why is what I am trying not allowed and not compiled as I would expect?

Upvotes: 4

Views: 1877

Answers (1)

cdhowie
cdhowie

Reputation: 169068

Yes, what you propose as the last code block is the right way to solve this.

Your first attempt does not work because you are defining a method with one argument, and the virtual method you are trying to override has zero. Giving arguments default values does not change the number of arguments the function takes, and therefore it does not match the no-arg overload in order to override it. All it does is instruct the compiler to insert the default value at any call sites that omit it, and in this case such a call would be ambiguous between the no-arg version and the one-arg version with a default value for the parameter.

Upvotes: 4

Related Questions