Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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";
   }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top