Accessing base class's method with derived cla

2020-03-01 17:42发布

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条回答
家丑人穷心不美
2楼-- · 2020-03-01 18:23

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.

查看更多
我想做一个坏孩纸
3楼-- · 2020-03-01 18:36
d.base::foo();

查看更多
Explosion°爆炸
4楼-- · 2020-03-01 18:37

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.

查看更多
家丑人穷心不美
5楼-- · 2020-03-01 18:42

we can call base class method using derived class object. as per below code.

#include<iostream.h>
class base
{
public:
void fun()
{
    cout<<"base class\n";
}
};
class der : public base
{
public:
void fun()
{
cout<<"derived class\n";
}
};
int main()
{

der d1;


d1.base::fun();


return 0;
} 

Output will be base class.

查看更多
登录 后发表回答