Sayzana Kibru
last year
Sayzanacountry asked

What is the difference between Function Overriding and Function Overloading?

Kelish Rai
Expert
last year
Kelish Rai answered

The main difference between function overloading and function overriding in C++ comes down to where and how the functions are defined.

1. Function overloading

  • Happens in the same class

  • Functions have the same name but different parameters (different number or types)

  • The compiler decides which function to call based on the arguments

Example:

#include 
using namespace std;

class Animal {
public:
    // Function with no parameters
    void make_sound() {
        cout << "Animal Sound" << endl;
    }

    // Overloaded function with an integer parameter
    void make_sound(int count) {
        cout << "Animal Sound (" << count << ") times" << endl;
    }
};

int main() {

    Animal a1;

    // Calls the function without parameters
    a1.make_sound();    // Output: Animal Sound

    // Calls the overloaded function with an integer argument
    a1.make_sound(10);    // Output: Animal Sound (10 times)

    return 0;
}

Here, calling make_sound() and make_sound(10) will call different versions of the function.

2. Function overriding

  • Happens between a base class and a derived class

  • Functions have the same name and parameters

  • The derived class function replaces the base class function when called via an object of the derived class

Example:

#include 
using namespace std;

class Animal {
public:
    // Function to make a generic animal sound
    void make_sound() {
        cout << "Animal Sound" << endl;
    }
};

class Dog: public Animal {
public:
    // Overrides the Animal class' make_sound() function
    void make_sound() {
        cout << "Woof Woof" << endl;
    }
};

int main() {

    // Create object of the child (Dog) class
    Dog dog1;

    // Calls the overridden function in child (Dog) class
    // and not base (Animal) class
    dog1.make_sound();

    return 0;
}

// Output: Woof Woof

Here, calling make_sound() on the Dog class executes the function of the Dog class, overriding the make_sound() function of the Animal class.

Also, one thing to note is just because function overloading happens within the same class doesn't mean it can't be used alongside inheritance.

You can still overload functions in a base class and its derived class, as long as the overloaded functions follow the usual rules—having the same name but different parameter lists.

C++
This question was asked as part of the Learn C++ OOP course.