on Leave a Comment

C++ Function Overriding

C++ Function Overriding

If both the base class and derived class defines a function with same name and arguments, it is called function overriding. Inheritance allows defining functions with same name and argument in both base class and derived class. Function overriding is also known as Method Overriding

Example of Function Overriding

class A
{
public:
         void display(){cout<<"Base Class";}
};
class B: public A
{
public:
         void display(){cout<<"Derived Class";}  //Function Overriding
};

If both base class and derived class define functions with same name but with different arguments then, it is not function overriding, actually it is function hiding. 

Program to Understand Function Overriding

#include<iostream>
using namespace std;
class Base
{
public:
    void display()
    {
        cout<<"\nI am in base class\n";
    }
};
class Derived: public Base
{
public:
    void display()
    {
        cout<<"\nI am in derived class\n";
    }
};
int main()
{
    Base B, *ptr;
    Derived D;
    B.display();
    D.display();

    cout<<"\nNow base class pointer containing the address of base class object";
    ptr = &B;
    ptr->display();

    cout<<"\nNow base class pointer containing the address of derived class object";
    ptr = &D;
    ptr->display();
    cout<<"\nThis is showing base class because of early binding";
    return 0;
}

OUTPUT:

I am in base class

I am in derived class

Now base class pointer containing the address of base class object
I am in base class

Now base class pointer containing the address of derived class object
I am in base class

This is showing base class because of early binding


0 comments:

Post a Comment