Search code examples
c++inheritancepure-virtual

What is the correct way to call the pure virtual member when another member exists with another signature?


I have a pure virtual interface class and a derived class that look like this

class IInterface
{
public:
    virtual void func() = 0;
};

class MyClass : public IInterface
{
public:
    void func(int i) { func(); }
};

The compiler complains that the call to func() in func(int i) does not take 0 arguments. What is the correct way to specify calling the pure virtual member?

The 2 solutions I came up with were

void func(int i) { static_cast<IInterface*>(this)->func(); }

and

void func(int i) { IInterface::func(); }

Are either of these viable? Is there a better way? Both seem clunky.


Solution

  • Bring the base class declaration into derived class scope with a using-declaration:

    class MyClass : public IInterface
    {
    public:
        using IInterface::func;
        void func(int i) { func(); }
    };
    

    Alternatively, convert this to a pointer to base will also work (i.e., your first option):

    void func(int i) { static_cast<IInterface*>(this)->func(); }
    

    IInterface::func(); won't work, as explicit qualification disables virtual dispatch.