Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ extend inherited functions

Tags:

c++

considering a simple inherited class:

class Base 
{
  void func() {
     cout << "base" << endl;
  }
};

class Derived : public Base
{
  void func() {
      cout << "derived" << endl;
  } 
};

if I run Derived::func() I get

derived

I would like to modify this code to get

base
derived

Something more similar to an extension than an overriding.

I've been able to get something similar with constructors, but not with normal functions.

Many thanks, Lucio

like image 747
Lucio Avatar asked Apr 16 '12 16:04

Lucio


2 Answers

class Derived : public Base
{
  void func() {
      Base::func();   // Call the base method before doing our own.
      cout << "derived" << endl;
  } 
};
like image 135
abelenky Avatar answered Sep 27 '22 19:09

abelenky


To access the base-class function from the derived class, you can simply use:

Base::func();

In your case, you would have this as the first line of the derived implementation of func().

like image 26
Oliver Charlesworth Avatar answered Sep 27 '22 17:09

Oliver Charlesworth