views:

71

answers:

3

when accessing foo() of "base" using derived class's object.

#include <iostream>

class  base
{
      public:
      void foo()
     {
        std::cout<<"\nHello from foo\n";
     }
};

class derived : public base
{
     public:
     void foo(int k)
     {
        std::cout<<"\nHello from foo with value = "<<k<<"\n";
     }
};
int main()
{
      derived d;
      d.foo();//error:no matching for derived::foo()
      d.foo(10);

}

how to access base class method having a method of same name in derived class. the error generated has been shown. i apologize if i am not clear but i feel i have made myself clear as water. thanks in advance.

+4  A: 
d.base::foo();

KennyTM
+6  A: 

You could add using base::foo to your derived class:

class derived : public base
{
public:
     using base::foo;
     void foo(int k)
     {
        std::cout<<"\nHello from foo with value = "<<k<<"\n";
     }
};

Edit: The answer for this question explains why your base::foo() isn't directly usable from derived without the using declaration.

Josh Townzen
but why base class's foo() is not accessible in derived class while I have inherited that base class...
CadetNumber1
@ashish: It is accessible (which means access specifiers of public/protected/private), but it is *hidden*. Read the question Josh linked: http://stackoverflow.com/questions/1628768/why-does-an-overridden-function-in-the-derived-class-hide-other-overloads-of-the
Roger Pate
+1  A: 

Add following statement to your derived class :

using Base::foo ;

This should serve the purpose.

When you have a function in derived class which has the same name as one of the functions in base class, all the functions of base class are hidden and you have to explicitly bring them in scope of your derived class as mentioned.

hype