Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism in C++ why is this isn't working?

class Base {
    public:
    virtual void f();
    void f(int);
    virtual ~Base();
};

class Derived : public Base {
public:
    void f();
};

int main()
{
    Derived *ptr = new Derived;
    ptr->f(1);
    delete ptr;
    return 0;
}

ptr->f(1); is showing the following error: "too many arguments in function call".

Why is this isn't possible? isn't derived inherited all the functions form base and is free to use any of them? I could call it explicitly and it would work but why isn't this allowed?

like image 433
Dannz Avatar asked Jan 09 '17 08:01

Dannz


2 Answers

What you are seeing is called hiding.

When you override the function void f() in the Derived class, you hide all other variants of the f function in the Base class.

You can solve this with the using keyword:

class Derived : public Base {
public:
    using Base::f;  // Pull all `f` symbols from the base class into the scope of this class

    void f() override;  // Override the non-argument version
};
like image 123
Some programmer dude Avatar answered Oct 01 '22 18:10

Some programmer dude


As mentioned by @Some Programming Dude : it is because of Hiding.

To understand hiding in relatively simpler language

Inheritance is meant to bring Baseclass variables / functions in Derived class.

But, on 1 condition : "If its not already available in Derived Class"

Since f() is already available in Derived, it doesn't make sense to look at Base class from compiler perspective.

That's the precise reason why you need to scope clarify while calling this function

void main()
    {
        Derived *ptr = new Derived;
        ptr->Base::f(1);
        delete ptr;
    }
like image 25
Deepak Kr Gupta Avatar answered Oct 01 '22 20:10

Deepak Kr Gupta