Wednesday, August 11, 2010

Overriding overloaded methods

#include <iostream>

using namespace std;

class B {
    public:
    virtual void A(string a, int b) {
        cout<<"B::A(string, int)"<<endl;
    }
    virtual void A(int c) {
        cout<<"B::A(int)"<<endl;
    }
};

class D : public B {
    public:
    virtual void A(string a, int b) {
        cout<<"D::A(string, int)"<<endl;
    }
};

int main() {
    D d;
    B* b = &d;
   
    b->A("a", 1);
    b->A(2);
   
    d.A("a", 1);
    d.A(2);

    return 0;
}

What do you think would be output of the above code?

Obviously, the output is not what most people will expect i.e.:
D::A(string, int)
B::A(int)
D::A(string, int)
B::A(int)


The code will instead give compilation error on line
     d.A(2);

This is because if you override one overloaded method, you need to override all of them, otherwise the ones you don't override are not available in the derived class.

To get things working you'll need to add following method in class D


virtual void A(int c) {
    B::A(c); 
}

As suggested by Kapil in the comments, the correct and elegant way to get it working is to add a declaration of A() in classD:

using B::A;