Calling a base method from a derived class

For example, I have this class:

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

I get a new one from him:

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

Is it possible to call a method from a derived class?

+3
source share
5 answers

Of course:

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

Btw, since it is Base::SomeFunc()not declared virtual, Derived::SomeFunc()hides it in the base class, and does not override it, which will undoubtedly cause some unpleasant surprises in the long run. Therefore, you can change your ad to

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

It also does this automatically Derived::SomeFunc() virtual, although you can explicitly declare it for the purpose of clarity.

+10
source
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 do that Derived::SomeFunc public.

+4
source

You do this by calling the function again with the parent class name prefix. You need to prefix the class name because there are several parents who can provide a function called SomeFunc. If there was a free function called SomeFunc, and you wanted to name it, then: SomeFunc would do the job.

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

Yes, you can. Note that you give the methods the same name without qualifying them as virtual, and the compiler should also notice it.

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

Source: https://habr.com/ru/post/1770569/


All Articles