OOP: INHERITANCE
Method Overriding
Method overriding means a derived class provides its own version of a base-class method with the same name and compatible signature.
Overriding is used when the derived class needs specialized behavior.
Basic Example
#include <iostream>
using namespace std;
class Animal {
public:
void sound() const {
cout << "Animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() const {
cout << "Bark" << endl;
}
};
int main() {
Dog dog;
dog.sound();
return 0;
}
Output:
Bark
Overriding With Virtual Function
For runtime polymorphism, the base function should be virtual.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() const {
cout << "Drawing shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() const override {
cout << "Drawing circle" << endl;
}
};
int main() {
Circle circle;
Shape* shape = &circle;
shape->draw();
return 0;
}
Output:
Drawing circle
Overriding vs Overloading
| Topic | Overriding | Overloading |
|---|---|---|
| Where | base and derived classes | same scope or class |
| Function name | same | same |
| Parameter list | usually same | different |
| Binding | runtime if virtual | compile time |
| Purpose | change inherited behavior | provide multiple forms |
Why Use override
The override keyword asks the compiler to check that the function really overrides a virtual base function.
If the signature is wrong, the compiler reports an error.
That protects you from accidental bugs.
Viva Answer
Method overriding occurs when a derived class defines its own version of a base-class method with the same signature. If the base method is virtual and called through a base pointer or reference, C++ uses runtime polymorphism to call the derived version.
Quick Check
- What must match for overriding?
- Why should base functions be marked
virtualfor runtime polymorphism? - What does
overridehelp the compiler check?