Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded final function in derived class [duplicate]

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!
like image 238
DejaVu Avatar asked Sep 19 '26 06:09

DejaVu


1 Answers

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();
like image 178
Vlad from Moscow Avatar answered Sep 20 '26 21:09

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!