10

I need to understand why C++ don't allow to access Grandparent overloaded functions in Child if any of the overloaded function is declared in Parent. Consider the following example:

class grandparent{
public:
    void foo();
    void foo(int);
    void test();
};

class parent : public grandparent{
public:
    void foo();
};

class child : public parent{
public:
    child(){
        //foo(1); //not accessible
        test();   //accessible
    }
};

Here, two functions foo() and foo(int) are overloaded functions in Grandparent. But foo(int) is not accessible since foo() is declared in Parent (doesn't matter if it declared is public or private or protected). However, test() is accessible, which is right as per OOP.

I need to know the reason of this behavior.

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
Jawad Akhtar
  • 172
  • 9

2 Answers2

11

The reason is method hiding.

When you declare a method with the same name in a derived class, base class methods with that name are hidden. The full signature doesn't matter (i.e. cv-qualifiers or argument list).

If you explicitly want to allow the call, you can use

using grandparent::foo;

inside parent.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Is there a reason why this behaviour is a good thing? (i.e. **why** as in for what reason, as opposed to *why* as in what causes it) – Sanjay Manohar Feb 17 '13 at 23:55
  • 1
    @SanjayManohar the only use I see would be to prevent mistakes - i.e. thinking you're calling a method from parent and actually calling a method from grandparent, because you miss-typed a parameter. And you can go around it with the `using` directive. – Luchian Grigore Feb 17 '13 at 23:57
  • @SanjayManohar see http://stackoverflow.com/questions/4837399/c-rationale-behind-hiding-rule – Luchian Grigore Feb 18 '13 at 00:10
1

Just imagine that a library has this class:

struct Base {
};

In your code you use that class as a base class:

struct Derived : Base {
    void f(int);
};

and now you write:

Derived d;
d.f('a');

And now you get the shiny new version 2.0 of that library, and the base class has changed a bit:

struct Base {
    void f(char);
}

If overloading applied here, your code would break.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165