Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

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

Interview Question (Programming)

What does the following function check?

bool f(unsigned int v)
{
  return ((v!=0)&&!(v & v-1));
}

(A) v is an odd number (B) v is a multiple of 2 (C) v is a power of 2 (D) v has a 0 bit

Answer :
(C) v is a power of 2

Explanation :
1) If v is a power of 2,

  • v is never 0 (even 2^0 = 1) and (v != 0) will always be 1(True).
  • (v & v-1) will always be 0(False) and hence their negation will always be 1(True).
2) If v is not a power of 2, either
  • v = 0, or
  • (v & v-1) is something other than 0 and their negation is 0(False)


Written by