Wednesday, June 19, 2013

Interview Question (Programming in C++)

Give the output of the following program :

class Animal
{
  public :
  virtual void draw()
  {
    cout<<”Animal”;
  }
};
class Leopard : public Animal
{
  public :
  virtual void draw()
  {
    cout<<”Leopard”;
  }
};
main()
{
  Leopard l;
  Animal *a=&l;
  l.draw();
}

(A) Leopard (B) Animal (C) LeopardAnimal (D) AnimalLeopard

Answer :
(A) Leopard

Explanation :
The virtual keyword  indicates to the compiler that it should choose the appropriate definition of the function draw not by the type of reference, but by the type of object that the reference refers to.
For more details on the use of virtual keyword : Reference

Written by

No comments:

Post a Comment