🎭 C++ Function Overriding – One Thing, New Way in Derived Class
In C++, function overriding means giving a new meaning to a function that’s already defined in a base class — but inside the derived class. It’s like your own way of doing something your parents also did! 😄
🔁 What is Overriding?
Overriding happens when a derived class defines a function that has the same name, return type, and parameters as a function in its base class.
To enable overriding, the base class should use the virtual keyword in the function.
📦 Syntax of Function Overriding
class Base {
public:
virtual void show() {
// base class version
}
};
class Derived : public Base {
public:
void show() override {
// derived class version
}
};
🔧 Example: Simple Overriding
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal makes sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks!" << endl;
}
};
int main() {
Animal* a;
Dog d;
a = &d;
a->sound(); // Dog's version will run
return 0;
}
🧠 Why Use Overriding?
- To customize behavior of inherited methods
- Useful in polymorphism – base pointers calling derived methods
- Gives flexibility and extensibility to your code
🚨 Rules of Overriding
- Function must have the same signature
- Base class function should be
virtual - Use
overridekeyword (C++11+) for clarity
❓ Override vs Overload
- Overriding: Same name, same parameters, different class
- Overloading: Same name, different parameters, same class
🧾 Summary
- Overriding means giving new behavior to a base class method
- Needs
virtualin base andoverridein derived (recommended) - Used in runtime polymorphism
- Remember: one thing, more than one version = override! 🎭