31 July, 2011

OOP interview questions and answers...

Q. What is difference between overloading and overriding?
A. Having same name methods with different parameters is called overloading, while having same name and parameter functions in base and drive class called overriding.

Q. What is Operator Overloading?
A. The operator overloading is a specific case of polymorphisms in which some or all of operators like +, -, %, etc. are treated as polymorphic functions and as such have different behaviors depending on the types of its operands.

Q. What is copy constructor?
A. Constructor which initializes it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.
for example:
Test t1(10); // calling Test constructor
Test t2(t1); // calling Test copy constructor
Test t2 = t1;// calling Test copy constructor
Copy constructors are called in following cases:
  • when a function returns an object of that class by value.
  • when the object of that class is passed by value as an argument to a function.
  • when you construct an object based on another object of the same class.
  • When compiler generates a temporary object.

Q. What is friend function?
A. As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

Q. What are virtual functions? Describe a circumstance in which virtual functions would be appropriate?
A. Virtual functions are functions with the same function prototype that are defined throughout a class hierarchy. At least the base class occurrence of the function is preceded by the keyword virtual. Virtual functions are used to enable generic processing of an entire class hierarchy of objects through a base class pointer. For example, in a shape hierarchy, all shapes can be drawn. If all shapes are derived from a base class Shape which contains a virtual draw function, then generic processing of the hierarchy can be performed by calling every shape’s draw generically through a base class Shape pointer.

No comments:

Post a Comment