Function overriding lets a child class change how a function works that it got from its parent. This helps make programs flexible and easy to change.
0
0
Function overriding in C++
Introduction
When you want a child class to do something different from the parent class for the same action.
When you have a general behavior in a parent class but need specific behaviors in child classes.
When you want to reuse code but still customize parts of it in child classes.
Syntax
C++
class Parent { public: virtual void functionName() { // parent version } }; class Child : public Parent { public: void functionName() override { // child version } };
The virtual keyword in the parent class means the function can be overridden.
The override keyword in the child class helps catch mistakes if the function does not match the parent.
Examples
Here,
Dog changes the sound function to print "Bark" instead of "Some sound".C++
class Animal { public: virtual void sound() { std::cout << "Some sound" << std::endl; } }; class Dog : public Animal { public: void sound() override { std::cout << "Bark" << std::endl; } };
Circle overrides draw to show a message specific to circles.C++
class Shape { public: virtual void draw() { std::cout << "Drawing shape" << std::endl; } }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing circle" << std::endl; } };
Sample Program
This program shows how the start function is overridden in the Car class. When we call start through a Vehicle pointer, the right version runs depending on the actual object.
C++
#include <iostream> class Vehicle { public: virtual void start() { std::cout << "Vehicle starting" << std::endl; } }; class Car : public Vehicle { public: void start() override { std::cout << "Car starting with key" << std::endl; } }; int main() { Vehicle* v1 = new Vehicle(); Vehicle* v2 = new Car(); v1->start(); // Calls Vehicle's start v2->start(); // Calls Car's start because of overriding delete v1; delete v2; return 0; }
OutputSuccess
Important Notes
Without virtual in the parent, the child version won't be called through a parent pointer.
Use override to help the compiler check your overriding is correct.
Summary
Function overriding lets child classes change parent class functions.
Use virtual in parent and override in child for safe overriding.
This helps make flexible and reusable code.