views:

69

answers:

5
+1  Q: 

Derived classes

Hello, 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?

+3  A: 
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.

Steve Townsend
You probably also want to make both "SomeFunc" functions virtual, so you can call the method on the base class and have it call the one on the derived class.
Colen
you forgot to remove the comment :)
codymanix
@codymanix - moved it up now, thanks
Steve Townsend
+7  A: 

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.

Péter Török
+1 for warning about hiding
Steve Townsend
Thanks for the answer.
Ockonal
A: 
class Child : public Base
{
   void SomeFunc()
   {
      Base::SomeFunc();
      std::cout << "Hello from child\n";
   }
};
codymanix
A: 

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";
   }
};
Keynslug
A: 

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.

stonemetal