Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

inheritance
base
derived
class
method

How to call an overridden function in C++

Educative Answers Team

A function can be overridden using inheritance to change its behavior. However, sometimes, we don’t need to completely alter or replace the functionality of the base (parent) class; instead, we need to add more functionality. In order to do this, the derived (child) class can call the parent’s function first (using the scope resolution operator ::) and then implement the additional functionality.

Re-using the parent’s code lets us write less code in the derived class.

svg viewer

Code

#include <iostream>
using namespace std;

class Base{
  public:
    void foo(){
      cout << "Base class functionality" << endl;
    }
};

class Derived: public Base{
  public:
    // Overriding foo():
    void foo(){
      Base::foo(); // Calling foo() of Base class
      cout << "Derived class functionality" << endl;
    }
};

int main() {
  Derived d;
  d.foo();

  return 0;
}

RELATED TAGS

inheritance
base
derived
class
method
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring