Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing base class's method with derived class's object which has a method of same name

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.

like image 351
Ashish Yadav Avatar asked Mar 13 '10 07:03

Ashish Yadav


People also ask

Can base and derived class have same name?

You cannot! class Derived : Base { public override void Method() { // This will call Base.

How do you access the original method of base class from the derived class?

Using a qualified-id to call a base class' function works irrespectively of what happens to that function in the derived class - it can be hidden, it can be overridden, it can be made private (by using a using-declaration), you're directly accessing the base class' function when using a qualified-id.

Can base class access methods of derived class?

base (C# Reference)The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.


2 Answers

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.

like image 183
Josh Townzen Avatar answered Nov 15 '22 19:11

Josh Townzen


d.base::foo();

like image 30
kennytm Avatar answered Nov 15 '22 20:11

kennytm