1

Consider the following code:

class Base
{
public:

    void Fun()
    {
    }
};

class Derived : public Base
{
public:

    void Fun(int x)
    {
    }
};

int main()
{
    Derived d;
    d.Fun(5);
    d.Fun();    // Compilation error
}

On compilation, the compiler complains that there is no version of Fun() that takes zero arguments. Why is this so? I can understand compiler hiding the base class version if the function signatures match in Base and derived classes, but why is the compiler not able to resolve both functions if they take different parameters/different no. of parameters?

Arun
  • 3,138
  • 4
  • 30
  • 41
  • 1
    Thanks for the link, I tried searching for this but wasn't having any luck with the various combinations and thus posted the question :-) – Arun Apr 02 '14 at 05:50
  • See my answer to this related question for a simple way to avoid the name hiding: http://stackoverflow.com/questions/22795432/overloaded-function-in-derived-class-c/22795554#22795554 – juanchopanza Apr 02 '14 at 07:01

3 Answers3

0

you have to create function body in derived class

void Fun()
{
}

Compile time first it will check function body in derived class.

Himanshu
  • 4,327
  • 16
  • 31
  • 39
0

compilation error, as there is no any 'Fun()' in derived class. You are calling Fun() by using derived class object. In CPP this is called as 'method hiding'. To solve this create function Fun() in derived class

void Fun() { }

Deva
  • 48
  • 6
  • `virtual` wouldn't change anything here. As for a sulution, see [this recent question](http://stackoverflow.com/questions/22795432/overloaded-function-in-derived-class-c/22795554#22795554). – juanchopanza Apr 02 '14 at 07:00
  • @juanchopanza I'm not talking about the situation here. I'm talking about '**function overriding**' where '**virtual**' takes care of overriding. I know 'function Overloading' has nothing to do with 'virtual',it is achieved by '**Name mangling**' technique by compiler. – Deva Apr 02 '14 at 07:20
  • Well, your answer is just confusing. – juanchopanza Apr 02 '14 at 07:21
0

You can use base class function if you are not overloading the function in derived class..

In the below example I changed the function name of derived class...

class Base
{
public:

    void Fun()
    {
    }
};

class Derived : public Base
{
public:

    void Fun1(int x)
    {
    }
};

int main()
{
    Derived d;
    d.Fun1(5);
    d.Fun();    // No Compilation error
}

If you want to overload the function in derived class then you will have to override the base class function. like this

class Base
{
public:

    void Fun()
    {
                printf("Base Class\n");
    }
};
class Derived : public Base
{
public:

    void Fun()
    {
        Base::Fun();
    }
    void Fun(int x)
    {
                printf("Derived Class\n");
    }
};

int main()
{
    Derived d;
    d.Fun(5);
    d.Fun();    // No Compilation error
} 
rajenpandit
  • 1,265
  • 1
  • 15
  • 21