Cover Image for Overriding Member Function in C++
142 views

Overriding Member Function in C++

The C++ override a member function in a derived class to provide a specialized implementation for that function. This is a fundamental concept in object-oriented programming and is commonly used when working with inheritance and polymorphism. To override a member function, follow these steps:

  1. Define a base class with a virtual function: Start by creating a base class that defines a virtual function. A virtual function is a function declared in a base class with the virtual keyword, which allows it to be overridden by derived classes.
C++
 class Base {
 public:
     virtual void print() {
         std::cout << "Base class print function" << std::endl;
     }
 };
  1. Create a derived class: Next, create a derived class that inherits from the base class.
C++
 class Derived : public Base {
 public:
     // Override the print function from the base class
     void print() override {
         std::cout << "Derived class print function" << std::endl;
     }
 };

Notice that in the derived class, we use the override keyword to indicate that we intend to override the print function from the base class. This helps catch errors at compile-time if there’s a mismatch in function signatures.

  1. Instantiate and use the classes: Now, you can create objects of both the base and derived classes and call the print function to see how the overridden version is called based on the object’s actual type.
C++
 int main() {
     Base baseObj;
     Derived derivedObj;

     Base* ptr = &baseObj; // Pointer to the base class
     ptr->print(); // Calls the base class print function

     ptr = &derivedObj; // Pointer to the derived class
     ptr->print(); // Calls the derived class print function

     return 0;
 }

In this example, even though ptr is a pointer to the base class, it correctly calls the overridden print function of the derived class when pointing to a Derived object, demonstrating polymorphism.

Remember that to successfully override a member function, the derived class’s function signature (return type, name, and parameters) must match the base class’s virtual function’s signature. Using the override keyword is good practice to ensure that you’re correctly overriding the function.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS