ITP

BCA - OOPS and Data Structures

What do you mean by method overriding

In : BCA Subject : OOPS and Data Structures

Method overriding happens when a child (derived) class has a method with the same name, return type, and parameters as a method in its parent (base) class, and redefines it to provide its own behavior.

Example :

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void speak() {
        cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void speak() override {  // this overrides Animal's speak
        cout << "Dog barks" << endl;
    }
};

int main() {
    Animal a;
    Dog d;

    a.speak(); // Outputs: Animal makes a sound
    d.speak(); // Outputs: Dog barks

    // Using a base class pointer
    Animal* ptr = &d;
    ptr->speak(); // Outputs: Dog barks, because of overriding and virtual function
}

About us

A truly open platform where you may ask questions and get answers. We also provide comprehensive and easy-to-understand answers to question papers.  discover...

Site status

Flag Counter

Privacy Policy

Sitemap