Calling base method from derived class

ぐ巨炮叔叔 提交于 2020-01-11 09:51:52

问题


I have, for example, such class:

class Base
{
   public: void SomeFunc() { std::cout << "la-la-la\n"; }
};

I derive new one from it:

class Child : public Base
{
   void SomeFunc()
   {
      // Call somehow code from base class
      std::cout << "Hello from child\n";
   }
};

And I want to see:

la-la-la
Hello from child

Can I call method from derived class?


回答1:


Sure:

void SomeFunc()
{
  Base::SomeFunc();
  std::cout << "Hello from child\n";
}

Btw since Base::SomeFunc() is not declared virtual, Derived::SomeFunc() hides it in the base class instead of overriding it, which is surely going to cause some nasty surprises in the long run. So you may want to change your declaration to

public: virtual void SomeFunc() { ... }

This automatically makes Derived::SomeFunc() virtual as well, although you may prefer explicitly declaring it so, for the purpose of clarity.




回答2:


class Child : public Base
{
   void SomeFunc()
   {
      // Call somehow code from base class
      Base::SomeFunc();
      std::cout << "Hello from child\n";
   }
};

btw you might want to make Derived::SomeFunc public too.




回答3:


You do this by calling the function again prefixed with the parents class name. You have to prefix the class name because there maybe multiple parents that provide a function named SomeFunc. If there were a free function named SomeFunc and you wished to call that instead ::SomeFunc would get the job done.




回答4:


class Child : public Base
{
   void SomeFunc()
   {
      Base::SomeFunc();
      std::cout << "Hello from child\n";
   }
};



回答5:


Yes, you can. Notice that you given methods the same name without qualifying them as virtual and compiler should notice it too.

class Child : public Base
{
   void SomeFunc()
   {
      Base::SomeFunc();
      std::cout << "Hello from child\n";
   }
};


来源:https://stackoverflow.com/questions/3980011/calling-base-method-from-derived-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!