Max Frai
Max Frai

Reputation: 64356

Calling base method from derived class

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?

Upvotes: 3

Views: 351

Answers (5)

Steve Townsend
Steve Townsend

Reputation: 54178

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.

Upvotes: 4

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116306

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.

Upvotes: 10

stonemetal
stonemetal

Reputation: 6208

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.

Upvotes: 1

Keynslug
Keynslug

Reputation: 2766

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";
   }
};

Upvotes: 0

codymanix
codymanix

Reputation: 29520

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

Upvotes: 0

Related Questions