Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding default arguments to virtual methods

Tags:

c++

In the following code, I would like to add new default argument 'z' to 'func' method without modifying subclasses. I get error C2259: 'CTest' : cannot instantiate abstract class error.

Is there anyway to do this without modifying all subclasses?

class ITest
{
public:
    virtual void func(int x, int y, char c, int z = 1) = 0;
};

class CTest : public ITest
{
public:
    void func(int x, int y, char c)
    {
    }
};
like image 840
tvr Avatar asked Jun 07 '26 18:06

tvr


1 Answers

What you want is not directly possible. The existing classes don't know of the z parameter, so can't use it. If you want to provide some new subclasses whose clients will be aware of the z and be able to use it, you can do this:

class ITest
{
public:
    virtual void func(int x, int y, char c) = 0;
    virtual void func(int x, int y, char c, int z)
    { func(x, y, c); }
};

This way, old classes work just as before, as will clients who call the 3-parameter version. You're also giving the option of new subclasses using z and new clients using the 4-parameter version.

like image 62
Angew is no longer proud of SO Avatar answered Jun 09 '26 08:06

Angew is no longer proud of SO