top of page
Writer's picturecompnomics

Function Overloading and Overriding in Inheritance


Function overloading allows you to define multiple functions with the same name but different parameter lists within the same class or scope. In C++, this concept can be extended to inheritance, leading to interesting interactions between base and derived classes.


Overloading in Base and Derived Classes

When a derived class inherits from a base class, it can overload functions that are already defined in the base class. This means that the derived class can have its own versions of the function with different parameter lists.


Example:

#include <iostream>

using namespace std;

class Base {
public:
    void func(int x) {
        cout << "Base::func(int)" << endl;
    }
};

class Derived : public Base {
public:
    void func(double x) {
        cout << "Derived::func(double)" << endl;
    }
};

int main() {
    Derived obj;
    obj.func(10); // Calls Derived::func(double)
    obj.func(10.5); // Calls Derived::func(double)
    return 0;
}

In this example, the Derived class inherits from the Base class. Both classes have a func function, but with different parameter types. When you call obj.func(10), the compiler will choose the Derived::func(double) version, as it's a more specific match.


Overriding in Base and Derived Classes

When a derived class inherits a virtual function from a base class, it can override that function to provide its own implementation. However, the parameter list of the overriding function must match the parameter list of the original virtual function in the base class.


Example:

#include <iostream>

using namespace std;

class Base {
public:
    virtual void func(int x) {
        cout << "Base::func(int)" << endl;
    }
};

class Derived : public Base {
public:
    void func(int x) override {
        cout << "Derived::func(int)" << endl;
    }
};

int main() {
    Base *ptr = new Derived();
    ptr->func(10); // Calls Derived::func(int)
    return 0;
}

In this example, the Derived class overrides the func function inherited from the Base class. When the ptr pointer, which is of type Base*, is used to call func, the compiler determines the correct implementation at runtime based on the dynamic type of the object pointed to by ptr.


Key Points:

  • Overloading allows you to have multiple functions with the same name but different parameter lists.

  • Overriding allows a derived class to provide its own implementation of a virtual function inherited from a base class.

  • When a function is overloaded, the compiler selects the appropriate function based on the number and types of arguments passed.

  • When a virtual function is overridden, the compiler determines the correct implementation at runtime based on the dynamic type of the object.

31 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page