Method Overloading vs Method Overriding in C++ and Python
0.0|0 ratingsLog in to rate
Understand compile-time versus runtime polymorphism by comparing overloading and overriding implementation in C++ and Python.
#oop#polymorphism#cpp#python#overloading#overriding
Compile-Time vs Runtime Polymorphism
Polymorphism takes two main shapes depending on when the system decides which method to run:
- Method Overloading (Compile-Time / Static Polymorphism): Defining multiple functions inside the same class scope with the same name but different parameter counts or types. The compiler links the call statically based on argument patterns.
- Method Overriding (Runtime / Dynamic Polymorphism): Redefining a method inside a subclass that already exists in the parent class with identical signatures. Resolved at execution time (dynamic dispatch).
Let's review code implementations in C++ and Python side-by-side.
C++ Overloading and Overriding implementation
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
class Calculator {
public:
// Method Overloading (compile-time)
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
};
class Parent {
public:
virtual void greet() { std::cout << "Hello from Parent" << std::endl; }
};
class Child : public Parent {
public:
// Method Overriding (runtime)
void greet() override { std::cout << "Hello from Child" << std::endl; }
};Python Overloading & Overriding implementation
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Calculator:
# Python does NOT support traditional overloading; defining the
# same method twice overwrites the first. We simulate overloading:
def add(self, a, b, c = None):
if c is not None:
return a + b + c
return a + b
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
# Method Overriding
def greet(self):
print("Hello from Child")Discussion
Loading discussion...