What is method overriding? Explain in reference of C++

A virtual or pure virtual method of parent class, re-written in child class with same signature and different body contents is called as method overriding.

It is used to achieve runtime polymorphism.

Use virtual keyword to mark a method as virtual or pure virtual.

Example

#include<iostream>
using namespace std;
class A
{
  public:
  virtual void show()
  { 
  cout <<"Welcome to A" << endl;
  }
};
class B : public A
{
 public:
  void show() //method overriding
  {
    cout <<"Welcome to B" << endl;
  }
};
class C: public B
{
  public:
  void show() //method overriding
  {
    cout <<"Welcome to C" << endl;
  }
};

main()
{

    A *p; //runtime polymorphism
  p=new A();
  p->show();
  p=new B();
  p->show();
  p=new C();
  p->show();
}

Output
Welcome to A
Welcome to B
Welcome to C



Comments

Popular posts from this blog

What is template?

Can we access private members of an instance?

What are wrapper classes in Java?