Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

overriding
communitycreator
c++
class

Can we override a function that is not a function of a class

Hasham Ahmad

Overview

In object-oriented programming, we have class, and class has two things member functions or data members.

Function Overriding

Function Overriding is defined as redefining the base class function in a derived class with the same name, parameters, and return type.

In function overriding, the overridden function in the parent class is referred to as the overriding function. The overriding function in the child class is referred to as the overriding function.

Overriding a function that is not a member function of the class

If the function is not a member function of the class, we cannot access that function with the help of class objects.

Note: Only the functions that the derived class inherited from the base class can be overridden.

Let’s understand this concept with the help of a scenario.

If the base class has a public member function, say, myfunc, then we can override the member function myfunc in the’ derived’ class.

But if the base class has a private member function, say, myfunc1, then the derived class cannot override the member function myfunc1.

Example

#include <iostream>
using namespace std;
class base
{
  private:
  void myfun1()
  {
    cout<<" Parent class private member function "<<endl;

  }
  public:
  void myfun()
  {
    cout<<"Parent class public member function"<<endl;
  }

};
class derived: public base
{
  public:
  void myfun()
  {
    cout<<"Child class public member function"<<endl;
  }

};

int main() {
  derived dri;// create drived class object
  dri.myfun();

  return 0;
}
Overriding the function

Explanation

  • Line 3 : We create base class.

  • Line 6: We create private member function myfunc1.

  • Line 12: We create public member function myfunc.

  • Line 18: We create drived class and inherit it with the base class.

  • Line 21: We create public member function myfunc and overridden it.

  • Lines 29 and 30: We create a derived class object and call it myfunc.

RELATED TAGS

overriding
communitycreator
c++
class
RELATED COURSES

View all Courses

Keep Exploring