Function Overriding In C++ - C++ Programming Tutorial
C++ Course / Functions / Function Overriding In C++

Function Overriding In C++

BLUF: Mastering Function Overriding In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Function Overriding In C++

C++ is renowned for its efficiency. Learn how Function Overriding In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, function overriding is a fundamental principle of OOPs (Object-Oriented Programming) that enables a subclass to redefine a method that is already defined in its superclass. This mechanism is employed to accomplish dynamic polymorphism.

Function Overriding is especially beneficial when there is a requirement to adjust or expand the functionality of an inherited function while avoiding alterations to the original base class. This feature allows us to supply a customized implementation of the function that is inherited from its base class.

Syntax

It has the following syntax:

Example

class Base_class {

public: //Access Modifier

    virtual void show() // Overriding Function

{

        cout << "It is the Base Class Function." << endl;

    }

};

class Derived_class : public Base_class {

public: //Access Modifier

    void show() override // Overriding Function

{  

        cout << "It is the Derived Class Function." << endl;

    }

};

In this arrangement, the function title, parameter, and output type functions remain identical.

C++ Function Overriding Example

Let's examine a basic illustration of Function overriding in C++. In this instance, we are redefining the eat method.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

class Animal {  

    public:  //Access Modifier

void eat(){    

cout<<"Eating...";    

    }      

};   

class Dog: public Animal    

{    

 public:  //Access Modifier

 void eat()    

    {    

       cout<<"Eating bread...";    

    }    

};  

int main(void) //Main Function

{  

   Dog d = Dog();    

   d.eat();  

   return 0;  

}

Output:

Output

Eating bread...

Rules for Function Overriding in C++:

Several rules for the function overriding in C++ are as follows:

  • Same Function Name: The function in the derived class should be the same name as in the base class.
  • Same Parameter: The function signature (parameters and return type) should be the same in both (base and derived class) classes.
  • Inheritance Requirement: The derived class must inherit from the base class.
  • Virtual Keyword: If the function in the base class is declared with virtual, it ensures proper function overriding and allows dynamic dispatch.
  • Access Modifier Restrictions: Access specifiers can be changed, but it is not recommended.
  • How does Function Overriding Work in C++?

In C++, function overriding is influenced by inheritance and the application of virtual keywords. Declaring a base class as virtual directs the compiler to enable dynamic dispatch. This mechanism ensures that the function invocation is determined during runtime according to the object's type, rather than the pointer's type.

If an inherited class instance redefines the virtual function of the base class and the function is invoked through a base class pointer or reference during runtime, the redefined function from the inherited class is run. This mechanism is enabled through a virtual table (vtable) managed internally by the compiler.

C++ Function Overriding with Access Specifiers Example:

Let's consider another instance to demonstrate the concept of function overriding with visibility modifiers in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Vehicle {

public: //Access Modifier

    virtual void startEngine() // Virtual function to allow overriding

{  

        cout << "Starting a generic vehicle..." << endl;

    }

};

class Car : public Vehicle {

public: //Access Modifier

    void startEngine() override // Overriding the function

{  

        cout << "Starting a car with a push button..." << endl;

    }

};

int main() //Main Function

{

    Vehicle* v1;  // Base class pointer

    Car c1;

    v1 = &c1;  // Assign address of derived class object to base class pointer

    v1->startEngine();  // Calls the overridden function

    return 0;

}

Output:

Output

Starting a car with a push button...

Explanation:

In this illustration, we've created a base class named vehicle class with a startEngine method that displays "initiating a standard vehicle". Subsequently, the car class is a subclass inheriting from the vehicle class, but it redefines the startEngine method.

Subsequently, a pointer of type Vehicle* is instantiated and linked to an instance of a car. Because the startEngine function is virtual, the redefined function within the Car class is executed dynamically during runtime, rather than the function from the base class.

Accessing Overridden Function in C++

There are various techniques to reach an overridden function in the subclass, including accessing it directly from the object or through the base class using pointers and references. Here are a few of the approaches:

1. Calling Overridden Function from Derived Class Directly

We have the ability to invoke the redefined function directly from the subclass by utilizing an instance of the subclass. This action triggers the execution of the function that was modified in the subclass.

Example of Overriding a Function Directly in a Derived Class:

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Base_class {

public: //Access Modifier

    virtual void display() {

        cout << "It is the base class display function" << endl;

    }

};

class Derived_class : public Base_class {

public:

    void display() override {

        cout << "It is the derived class display function" << endl;

    }

    void callBaseFunc() {

        Base_class::display(); //It calls base class function directly

    }

};

int main() //Main Function

{

    Derived_class object;

    object.display();           //It calls overridden function in Derived

    object.callBaseFunc();  //It calls the base class function 

    return 0;

}

Output:

Output

It is the derived class display function

It is the base class display function

Explanation:

In this instance, the object.display method triggers the redefined function in the subclass, whereas the obj.callBaseFunction method invokes the display function from the base class explicitly within the subclass.

2. Calling Overridden Function via Base Class Pointer or Reference

When a function is invoked using a pointer or reference to a base class, and this function has been redefined in the derived class, the program will execute the overridden version of the function from the derived class.

Example of Overriding a Function Using a Pointer or Reference to a Base Class:

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Car {

public: //Access Modifier

    virtual void showBrand() {

        cout << "Generic Car Brand" << endl;

    }

};

class Mahindra : public Car {

public:

    void showBrand() override {

        cout << "Brand Name: Mahindra" << endl;

    }

};

class Kia : public Car {

public:

    void showBrand() override {

        cout << "Brand Name: Kia" << endl;

    }

};

int main() //Main Function

{

    Mahindra mahindraCar;

    Kia kiaCar;

    // Base class pointer

    Car* carPtr;

    carPtr = &mahindraCar;

    carPtr->showBrand();  

    carPtr = &kiaCar;

    carPtr->showBrand(); 

    // Base class reference

    Car& carRef = kiaCar;

    carRef.showBrand();  

    return 0;

}

Output:

Output

Brand Name: Mahindra

Brand Name: Kia

Brand Name: Kia

Explanation:

In this instance, the Car base class contains a virtual method named showBrand. The Mahindra and Kia brands implement this method with brand-specific details. Leveraging a base class pointer or reference enables the invocation of the overridden function dynamically, determined by the specific object rather than the pointer or reference type.

3. Calling Overridden Function using Scope Resolution Operators

We have the option to utilize the scope resolution operators (::) to reach the overridden function in the C++ programming language.

Example of Function Overriding with Scope Resolution Operators:

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class base_Class {

   public: //Access Modifiers

    void print() {

        cout << "This is the Base Function." << endl;

    }

};

class derived_Class : public base_Class {

   public:

    void print() {

        cout << "This is the Derived Function." << endl;

    }

};

int main() //Main Function

{

    

    derived_Class a1, a2;

    a1.print();

    // Using the scope resolution operator ::

    a2.base_Class::print();

    return 0;

}

Output:

Output

This is the Derived Function.

This is the Base Function.

Advantages and Disadvantages of Function Overriding:

Several benefits and drawbacks of Function Overloading in C++ are outlined below:

Advantages:

  • Function overriding provides the option for runtime polymorphism that lets flexible and dynamic code.
  • It helps to save the memory space.
  • It makes code re-usability easier.
  • In function overriding, the child class can access the function of the parent class.
  • We can specialize the inherited behaviors of the base class functions to meet a specific class.
  • Disadvantages:

  • Static functions can never be overridden.
  • It cannot be performed inside the same class. Therefore, we are required to implement inheritance.
  • C++ Function Overriding MCQs

  1. Which of the following statements is true about function overriding in C++?
  • Inheritance is needed only for multiple functions.
  • Overriding can be applied without using inheritance.
  • Inheritance should not be required when overriding is used in the program.
  • Inheritance must be used to use function overriding.
  1. How can we access the overridden method of the base class from the derived class in C++?
  • Using dot operator
  • Using scope resolution operator
  • Using arrow operator
  • Cannot be accessed once overridden
  1. Which keyword is used to achieve runtime polymorphism in C++?
  • virtual
  • override
  • static
  • friend

a) virtual

What is the output of the code snippet below?

Example

class Base_class {

public:

    virtual void show() { cout << "This is the Base Function"; }

};

class Derived_class : public Base_class {

public:

    void show() override { cout << "This is the Derived Function"; }

};

int main() {

    Base_class* bptr = new Derived_class();

    bptr->show();

    return 0;

}
  • This is the Base Function
  • This is the Derived Function
  • Compilation Error
  • Runtime Error
  1. Can a private member function in the base class be overridden in C++?
  • A) Yes
  • B) No
  • C) Only if declared virtual
  • D) Only if declared public

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience