Method overriding

  •  when there are two functions of same name , one in base class and one in derived class, and when you call that function one get executed while one get overridden and that process is called as method overriding.
  • It is also know as run time polymorphism.
(when there are same name function in derived class and base class and you call that function from the derived class object the derived class function will be executed because object executes function present inside its class first)


#include<iostream>
using namespace std;
class A{
  public:
  void display(){
      cout<<"Class A"<<endl;
  }
};
class B:public A{
  public:
  void display(){
      cout<<"Class B"<<endl;
  }
};

int main(){
 B b;
 b.display();
  return 0;
}


//output
//class B

There are two ways for method overriding 

  1. using scope resolution operator.
  2. using pointer.

1. Using Scope Resolution operator

Syntax:

objectname.parentclassname::method();


#include<iostream>
using namespace std;
class A{
  public:
  void display(){
      cout<<"Class A"<<endl;
  }
};
class B:public A{
  public:
  void display(){
      cout<<"Class B"<<endl;
  }
};

int main(){
 B b;
 b.A::display();
  return 0;
}


//output
//class A

  • here, in first program class A display was overridden by class B so after that we use scope resolution operator due to which class B display got overridden by class A display. This is how method overriding works.

2. using pointer



#include<iostream>
using namespace std;
class A{
  public:
  void display(){
      cout<<"Class A"<<endl;
  }
};
class B:public A{
  public:
  void display(){
      cout<<"Class B"<<endl;
  }
};

int main(){
A *a;
B b;
a = &b;
a->display();
  return 0;
}


Post a Comment

Previous Post Next Post