prakhar3agrwal
prakhar3agrwal

Reputation: 346

Not able to call base class function

I don't understand why this code gives compilation error, it is not a case of overriding because the parameter list in the base and child class is different, so can anyone help me on this.

#include <iostream>
using namespace std;
class Base
{
    public:
    void func ( )
    { 
        cout<< a ;
    }

    protected:  
    int a;
};

class Drived : public Base
{
    public:
    void func ( int inVal) 
    { 
        cout<< b <<"-> "<<inVal;
    }

    protected:
    int b;
 };

int main(int argc, char* argv[])
{
    Drived d;
    d.func(); //->Compilation error why and how can we avoid it?
    return 0;
}

Upvotes: 1

Views: 278

Answers (3)

Jonathan Potter
Jonathan Potter

Reputation: 37122

The func in Drived hides the one in Base. The easiest way to call it is to specify the scope:

d.Base::func();

If Base::func was a virtual function however this would disable virtual dispatch. An alternative solution is to bring the Base declaration into the Drived class scope with a using-declaration:

class Drived : public Base
{
public:
    using Base::func;
    void func(int inVal)
    ...
};

Upvotes: 1

Spanky
Spanky

Reputation: 1130

paste this line and it will work

Drived d;
d.func(1); //whats changed?
return 0;
return 0;

I believe you should figure out the difference yourself. Its not that difficult. have a look

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490048

When looking for a matching function, the compiler searches through successively larger scopes until it finds a scope that contains the correct name. Then (for a function call) it collects together everything in that scope with that name, and does overload resolution on them to find the right one to call. If none of them can be called, it stops, and it's an error. It does not continue to search through more scopes looking for another function to call.

To make things work, you can bring the name of the base class function into scope in the derived class:

class Derived : public Base
{
    public:
    using Base::func;   // <--- this is what we added
    void func ( int inVal) 
    { 
        cout<< b <<"-> "<<inVal;
    }

    protected:
    int b;
 };

With that in place, the compiler will treat Derived::func and Base::func as an overload set, and see that you haven't passed any parameters so Base::func is the only one you could be calling, so that's what it resolves to.

Upvotes: 4

Related Questions