0

Why does d.f(1) call Derived::f in this code?

Does the using Base::f play a role in deciding which f will be called?

#include <iostream>
using namespace std;

struct Base {
    void f(int){
        cout << "\n f(Base) is called" ;
    }
};
struct Derived : Base {
    using Base::f ;    //  using-declarations  but still Drived function is called
    void f(int){
        cout << "\n f(Derived) is called" ;
    }
};
void use(Derived d)
{

    d.f(1);     // calls Derived::f
    Base& br = d ;
    br.f(1);        // calls Base::f
}

int main() {

        Derived d;
        use (d);
        return 0;
}
Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88
test program
  • 281
  • 1
  • 8
  • 1
    `using Base::f` is only for cases, when you don't have an overidden function in `Derived`. As soon you have a declaration/definition there, this one is called. – πάντα ῥεῖ Feb 05 '15 at 18:38
  • Your sample would make more sense, if Base::f and Derived::f have different arguments (Here you hide the one and only (using) function with the derived function) –  Feb 05 '15 at 18:41
  • When I run your code in VS2013 Update 4, the it calls derived, then base. Are you saying it calls derived, then derived for you? – Moby Disk Feb 05 '15 at 18:57
  • Yeah, it calls derived first, then base. http://coliru.stacked-crooked.com/a/cdd10f796300f63e Am I misunderstanding the problem? What is desired here? – Moby Disk Feb 05 '15 at 18:58
  • I just edit the question to ensure the real question is stated up front. The initial text was a bit confusing - namespaces aren't really relevant for example – Aaron McDaid Feb 05 '15 at 19:00
  • Oh, okay! thanks for the clarification. I will remove my answer then. – Moby Disk Feb 05 '15 at 19:00
  • 1
    problem is from this point that i was expecting Derived::f wont be called – test program Feb 05 '15 at 19:03
  • Why did you expect that `d.f(1)` would *not* called `Derived::f`? Is it because the `using Base::f` might 'copy' `Base::f` into `Derived` and therefore it would 'hide' `Derived::f`? – Aaron McDaid Feb 05 '15 at 19:06

1 Answers1

5

The function void f(int) in the derived class hides the function in the base as they have the same name and parameters.

It is explained here: Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined. If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

Matt
  • 6,010
  • 25
  • 36