What is Function Overloading vs Function Overriding in C++?
Many beginners get confused between Overloading and Overriding. Both look same because both use same function name. But they are totally different. Let's understand in simple words.
What is Function Overloading?
When we create many functions with same name but different parameters in same class, it is called Function Overloading.
Example: add(2, 3) and add(2.5, 3.5) - name is same, but parameters are different.
Example of Function Overloading:
include
using namespace std;
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
};
int main() {
Calculator c;
cout << c.add(2, 3) << endl;
cout << c.add(2.5, 3.5) << endl;
cout << c.add(1, 2, 3) << endl;
return 0;
}
Output:
5
6
6
Here C++ decides at compile time which function to call. This is called Compile Time Polymorphism.
What is Function Overriding?
When child class creates same function again which is already in parent class, it is called Function Overriding.
Here function name and parameters are same, but work is different.
Example of Function Overriding:
include
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
}
};
int main() {
Animal* a;
Dog d;
a = &d;
a->sound();
return 0;
}
Output:
Dog barks
Here child class overrides the parent function. This is called Run Time Polymorphism.
Overloading vs Overriding - Easy Difference:
Overloading: Same class, same name, different parameters. Happens at Compile Time. No Inheritance needed.
Overriding: Parent and Child class, same name, same parameters. Happens at Run Time. Inheritance is needed.
Conclusion:
Overloading means many versions of same function. Overriding means child class changes parent function. Both make our code clean and easy.
I have tested this code myself and it works perfectly.
Top comments (0)