Search code examples
c++inheritanceoperator-overloadingabstract-class

Overload a virtual method in a derived class so it takes more parameters in C++


I have an abstract class A with the pure virtual method void foo(int a) = 0

Then I have several classes that inherit from A and all of them define the method foo. But I need one of them, B, to make it so foo takes an extra parameter, int b, so sort of an overload.

Then I would like to do this:

A *bInstance = new B();
bInstance -> foo(1, 2);

But I get an error telling me that foo is taking too many parameters.

Writing this, I realize it's kind of a weird thing to do so maybe you can't do this and it's good that you can't do it. But in case it is possible, please do tell me how I should go about it.


Solution

  • You can use the overloaded function of B only if the pointer to use is of type B.

    See:

    #include <iostream>
    #include <memory>
    
    class A{
    public:
      virtual void foo(int a) = 0;
    };
    
    class B : public A
    {
    public:
        virtual void foo(int a) override
        {
    
        }
        void foo(int a, int b)
        {
            std::cout << a << "," << b;
        }
    };
    
    int main(){
        auto b = std::make_shared<B>();
        b->foo(1, 2);
        
        //to use a:
        A* aPtr = b.get();
        aPtr->foo(1);
    
        return 0;
    }