Search code examples
c++arrayspointerssubclassdefault-value

Use default value of Subclass method in an array of Base class


Is there any way that cout << a[0]->function(); can give a 5 instead?

At the moment, it takes the default value of the base class and runs the method of the subclass.

But I want it to run the method of the subclass and take the default value of the subclass.

class Basis
{
public:
    virtual int function(int i = 1) { return 2; }
};

class Sub : public Basis
{
public:
    int function(int i = 5) override { return i; }
};

int main()
{
    Basis* a[2];
    a[0] = new Sub();
    cout << a[0]->function(); //gives 1
}

Solution

  • Your code is calling function() via a Basis* pointer, so it is going to use the default value defined by Basis, there is no way for Sub to override that. Calling function() via a Sub* pointer would use the default value defined by Sub instead.

    So, given the code you have shown, the easiest way I can think of doing what you are asking for is to use function overloads, eg:

    class Basis
    {
    public:
        virtual int function() { return function(1); }
        virtual int function(int i) { return 2; }
    };
    
    class Sub : public Basis
    {
    public:
        int function() override { return function(5); }
        int function(int i) override { return i; }
    };
    
    int main()
    {
        Basis* a[2];
        a[0] = new Basis();
        a[1] = new Sub();
        cout << a[0]->function(); //gives 2
        cout << a[1]->function(); //gives 5
    }