Search code examples
c++c++11polymorphismoverloadingfinal

Overloaded final function in derived class


How can I use final overloaded function from derived class?
Compiler says 'no matching function for call to 'B::foo()''.

class A
{
public:
    virtual void foo() final
    {
        std::cout << "foo";
    }
    virtual void foo(int b) = 0;
};

class B : public A
{
public:
    void foo(int b) override
    {
        std::cout << b;
    }
};

//Somewhere
B* b = new B;
b->foo(); //Error

But it works without overloading.

class A
{
public:
    virtual void foo() final
    {
        std::cout << "foo";
    }
};

class B : public A
{
};

//Somewhere
B* b = new B;
b->foo(); //Works!

Solution

  • This declaration in class B

    void foo(int b) override
    {
        std::cout << b;
    }
    

    hides all other functions with the same name declared in class A (excluding of course the overriden function).

    You can either call the function explicitly like this

    b->A::foo(); 
    

    Or include using declaration

    using A::foo;
    

    in the definition of class B.

    Or you can cast the pointer to the base class pointer

    static_cast<A *>( b )->foo();