Skip to main content

C++ Code for Function Overriding Using Virtual Keyword

Example

Function Overriding in OOP occurs when a derived class has its own implementation of a function which already exists in the base class.

The base class virtual function should be declared and redefined in the derived class.
This also allows Runtime Polymorphism where the relevant function is chosen at run time based on the type of object used.

#include <iostream>
using namespace std;
class Animal {
public:
    virtual void sound() {   // Virtual function
        cout << "Animal makes a sound" << endl;
    }
};
class Dog : public Animal {
public:
    void sound() override {   // Overriding base class function
        cout << "Dog barks" << endl;
    }
};
class Cat : public Animal {
public:
    void sound() override {
        cout << "Cat meows" << endl;
    }
};
int main() {
    Animal* a1;
    Dog d;
    Cat c;
    a1 = &d;
    a1->sound();   // Calls Dog's sound()
    a1 = &c;
    a1->sound();   // Calls Cat's sound()
    return 0;
}

Output

Dog barks Cat meows

Explanation

  1. Animal is a base class that includes virtual sound function.

  2. Derived classes Dog and Cat use the same function by using virtual keyword.

  3. Our base class pointer (Animal* a1) is pointed to both Dog and Cat objects in main.

  4. Due to the virtual nature of this function, the call a1->sound() is not resolvable at compile-time (but only at runtime).

  5. When a1 says to the Dog what it sounds like, it calls to the Dog what it sounds like.

    • Instead, when a1 points at a Cat, it calls the sound () of Cat.

    • When a1 is pointing at a Cat, then it calls the sound() of Cat.

This demonstrates Function Overriding in C++ as a form of Runtime Polymorphism.


Thanks for reading 💗!


If you found this post useful:

⮕  Share it with others who might benefit.
⮕  Leave a comment with your thoughts or questions—I’d love to hear from you.
⮕  Follow/Subscribe to the blog for more helpful guides, tips, and insights.

Comments

Popular posts from this blog

Artificial Intelligence vs Machine Learning vs Deep Learning: Key Differences Explained

  Everywhere you look today, people are talking about AI, Machine Learning, and Deep Learning . Tech companies use these terms in product launches, news headlines throw them around, and chances are you’ve already heard them in your classroom, workplace, or even casual conversations. But here’s the catch,  most people don’t actually know the difference . Some think AI, ML, and DL are the same thing. Others assume they’re just fancy names for robots or algorithms. So, what really sets them apart? Is AI just about robots? Is Machine Learning smarter than AI? And why does everyone say Deep Learning is the future? In this blog, we’ll break down introductory part of  AI, ML, and DL in simple and easy language with examples, diagrams, and real-life applications — so by the end, you’ll never be confused again. Think of Artificial Intelligence (AI), Machine Learning (ML), and Deep Learning (DL) like math sets . AI  is the  biggest set (Universal Set) ...

All About Inheritance in OOP: Explained with Real-Life Examples

  The first thing that comes to mind when  you hear the word  inheritance,  is passing something down from parents to children . In Object-Oriented Programming, it works in a very similar way—it allows one class (child class) to inherit properties and behaviors from another class (parent class). This concept makes code reusable, organized, and easier to maintain . Let’s explore inheritance step by step with real-time analogies to make it super simple. What is Inheritance in OOP? In OOP, inheritance is a concept in which a class inherits the properties (variables) and behaviors (methods) of other classes. Common features are defined in the parent class . These features are extended by the child class which is capable of adding its own features.. It is best to consider it as a family tree : a child takes after a parent in terms of eye color or height but can also possess an individual characteristic. Why Use Inheritance? Code Reusability – No need t...

Why Python Is the Best Programming Language for Machine Learning, AI, and Deep Learning

  Artificial Intelligence (AI), Machine Learning (ML), and Deep Learning (DL) have become some of the most transformative technologies of our time. From self-driving cars and recommendation systems to chatbots and healthcare diagnostics, these technologies are reshaping industries at an incredible pace. But have you ever wondered: Why do most AI researchers, data scientists, and developers prefer Python over other programming languages? In this blog, we’ll explore in depth why Python has emerged as the most popular and powerful language for AI, ML, and DL development . 1. Simplicity and Readability – Focus on Problem Solving, Not Syntax Complex mathematics and algorithms are some of the greatest challenges that newcomers in the world of AI/ML face. Python eases this load by providing a clean syntax that is easy to read. Let’s look at three concrete examples where Python’s clean syntax helps newcomers in AI/ML handle complex mathematics and algorithms more easily compared to ot...