2

Before asking my question I tried searching the web, but I'm not sure what terms I need to use, and I didn't find an explanation to my problem. If such an answer allready exists, feel free to just point me to it :)

Here is a small sample:

class IObject;
class ClassA;

class Base {
public: void Method(IObject * object) {}
};

class Derived : public Base {
public: void Method(ClassA * objet) {}
};

class IObject {};
class ClassA : public IObject {};

int main(int argc, char ** argv) {
    IObject * object = new ClassA();
    Derived derived;
    derived.Method(object);
    delete object;
    return 0;
}

This doesn't compile because the compiler tries to use the Derived::Method version of the method, even though there exists a perfectly valid Base::Method for the given object.

To make this compile (and work), I need to add the following in Derived:

class Derived : public Base {
public:
    // adding this line make the Base::Method visible to the compiler ??
    using Base::Method;
    void Method(ClassA * object) {}
};

After adding this line, everything works as intended. What I don't understand is : why ? If I rename Base::Method to Base::BaseMethod, I can call it from the Derived instance without any problem. Why does the compiler fails to find the correct method based on the parameter's type ??

Citron
  • 1,019
  • 9
  • 24
  • Yep, now that I know which terms to use (e.g. "function hiding") I found a lot of answers and duplicate questions :) – Citron Jun 24 '13 at 09:41

2 Answers2

3

This rule is known as Function hiding in C++.
A method in derived class with same name as of the Base class method hides the base class method in derived class. The users of the derived class can only see the derived class method irrespective of the function parameter types. The base class method is simply not present in Derived class scope. So the overload resolution doesn't work as you expect it to.
To be able to access the Base class method in derived class you explicitly need to tell the compiler to bring it in the derived class scope with the using declaration.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • And thank you too for the link. From what I understood, this rule was introduced to avoid problems with implicit casting. Good to know :) – Citron Jun 24 '13 at 09:43
2

This is called member function hiding: As soon as you have a function in a derived class having a different signature than a function with the same name in the base class, the base class versions of the functions are invisible to the derived class and its clients. Here's the reason why this was introduced.

Community
  • 1
  • 1
Ralph Tandetzky
  • 22,780
  • 11
  • 73
  • 120