Calling base method from derived class

╄→尐↘猪︶ㄣ 提交于 2019-12-01 22:04:41

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.

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.

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.

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

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