What is the difference between overloading and overriding in C++?
| Point | Overloading | Overriding |
|---|---|---|
| Where | Same scope | Base and derived class |
| Parameters | Different | Same |
| Needs virtual | No | Yes (for run time behavior) |
| Decided | Compile time | Run time |
#include <iostream>
struct Base {
virtual void f() const { std::cout << "Base::f\n"; }
void g(int) const { std::cout << "g(int)\n"; }
void g(double) const { std::cout << "g(double)\n"; } // overloading
};
struct Derived : Base {
void f() const override { std::cout << "Derived::f\n"; } // overriding
};
int main() {
Derived d;
const Base& b = d;
b.f();
b.g(1);
b.g(1.5);
}
Output
Derived::f
g(int)
g(double)
See Polymorphism and Function Overloading.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |