Monday, 26 April 2021

Virtual Function in C++ Qus - 2

Consider the situation when we don't use the virtual keyword.

 


class A

{

public:

   

void show()

  {

    

      cout<<"Hello"<<endl;

  }

  

};


class B: public A

{

    public:

   

   void show()

  {

    

      cout<<"India"<<endl;

  }

    

 

};

int main() {

 

    A *a;  

    B b;  

    a = &b;  

   a->show();  

    return 0;  

 

 

}


Output:

Hello


Now, when we  use the virtual keyword.


class A

{

public:

   

 virtual void show()

  {

    

      cout<<"Hello"<<endl;

  }

  

};


class B: public A

{

    public:

   

   void show()

  {

    

      cout<<"India"<<endl;

  }

    

 

};

int main() {

 

    A *a;  

    B b;  

    a = &b;  

   a->show();  

    return 0;  

 

 

}


Output:

India

No comments:

Post a Comment