C++ – Is Overriding Pure Virtual Function with Default Arguments Good?

cc++14object-orientedvirtual-functions

Is overriding a pure virtual function with default arguments good or bad?

class Base {
public:
    virtual int func(int i, int j = 10) = 0;
};

class Derived : public Base {
public:
    int func(int i, int j = 20) override;
};

Best Answer

I would not venture to do this. At best, as @Bart van Ingen Schenau said, it will cause you nasty surprises. Furthermore, I would not even recommend using default parameters in virtual functions in the first place. If you want to have something like that, I suggest doing something like this:

class Base {
public:
    virtual int func(int i, int j) = 0;
    virtual int func(int i)
    {
        func(i, 10);
    }
};

class Derived : public Base {
public:
    int override func(int i, int j)
    {
        //Some override code
    }

    int override func(int i)
    {
        func(i, 20);
    }
};

You provide the basic funcionality with the most specific method, and provide easier methods to developers using your classes so they do not have to worry about default values for parameters. That way, you have bigger flexibility for intervention and you always know which method was called and how.