简体   繁体   中英

C++ extend inherited functions

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

class Derived : public Base
{
  void func() {
      Base::func();   // Call the base method before doing our own.
      cout << "derived" << endl;
  } 
};

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() .

Using Base::func(); is correct like a few others already stated.

Remember the constructor for the base class will always get called first, then the constructor for the derived class.

You've talked about constructor, a derived class's constructor will call base class's one, no matter whether you use an inherited constructor, it makes sense because a derived class should be able to construct the members inherited from the base class. And by default, constructor wouldn't be inherited.

But, the "normal" method goes the much different way.

First, please sure that in most of the time, it's not necessary for a method in derived class to call the same-name method in base class, and on the contrary, it will cover base class's one, although it did inherit it.

So if you really want to call base class one, you should tell complier explicitly. Using baseclass::somemethod will fulfill your request.

You can't do so. You'll have to do like

 Void derived:: func()
 {
  this->func(); /*you should use 'this pointer' to 
  access the base class functions*/
  cout<<"derived";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM