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

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
    virtual int function() { return function(1); }
    virtual int function(int i) { return 2; }

class Sub : public Basis
    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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top