Inheritance and Polymorphism in C++ and Python
0.0|0 ratingsLog in to rate
Master subclassing, method overrides, dynamic dispatch, and virtual tables in C++ compared to duck typing in Python.
#oop#inheritance#polymorphism#cpp#python
Concepts of Inheritance and Polymorphism
Inheritance allows a child class (subclass) to inherit fields and methods from a parent class (superclass), promoting code reuse.
Polymorphism allows objects of different classes to respond to the same method signature in unique ways.
- In C++, dynamic polymorphism requires the
virtualkeyword and is resolved at runtime via a Virtual Method Table (vtable). - In Python, polymorphism is natural and resolved dynamically at runtime (often described as "duck typing").
C++ Inheritance & Polymorphism Implementation
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
class Animal {
public:
// virtual keyword enables runtime dynamic dispatch
virtual void makeSound() {
std::cout << "Some animal sound" << std::endl;
}
virtual ~Animal() = default; // Destructor should be virtual
};
class Dog : public Animal {
public:
void makeSound() override { // override keyword enforces safety
std::cout << "Bark!" << std::endl;
}
};
int main() {
Animal* myPet = new Dog(); // Base class pointer to child instance
myPet->makeSound(); // Prints "Bark!" due to vtable lookup
delete myPet;
return 0;
}Python Inheritance & Polymorphism Implementation
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Animal:
def make_sound(self):
print("Some animal sound")
class Dog(Animal): # Inheriting syntax
def make_sound(self):
print("Bark!")
# Duck Typing in python
def play_animal_sound(animal_instance):
animal_instance.make_sound()
pet = Dog()
play_animal_sound(pet) # Prints "Bark!"Vtable vs Dynamic Typing Trade-offs
Example
C++ vtable lookups add a microsecond indirection overhead but guarantee compile-time type checks. Python's dynamic lookup allows passing any object that responds to make_sound() (Duck Typing), providing unparalleled speed in development at the cost of compile-time error checks.
Discussion
Loading discussion...