Thursday, September 12, 2013

C, C++ Interview Questions and Answers

1. How can you keep track of instances of a class?

We can keep track of instances of a class using a static variable. Define a static member within the class, increase its value by 1 within the constructor and decrease the same by 1 in destructor. Value of that static variable at any time will give you the value of number of instances of that class.



2. What is the property of static data members?

When a data member is declared as static, only one copy of the data is maintained for all objects of the class. Static data members are not part of objects of a given class type. The data member is declared in class scope, but definition is performed at file scope.

3. Describe a situation where you can't use this pointer.

Static member functions do not have this pointer. So in case of static member function we cannot use this pointer.

4. Explain concept of polymorphism.
Polymorphism is the ability to use an operator or method in different ways .Benefits of polymorphism:-

I. Helps in reusability of code.

II. Provides easier maintenance of applications.

C++ provides three different types of polymorphism.

I. Virtual functions

II. Function overloading

III. Operator overloading



5. What is the necessary condition for implementing run time polymorphism?

The run-time polymorphism is implemented with inheritance and virtual functions.



6. What is abstract base class?

An abstract base class is a class that has one or more pure virtual member functions. We cannot make an object of such class.



7. Explain early binding and late binding.

In brief, answer is early binding refers to compile time binding and late binding refers to runtime binding.

In CPP late binding is related to virtual functions.


8. What is this pointer? Write a code to show the use of this pointer.

The 'this' pointer is a hidden parameter of non-static member functions. When we declare a function the compiler adds an extra parameter to function's prototype. The type of the parameter depends on how the function is declared. Static member functions do not have a 'this' pointer.



9. Explain shallow copy and deep copy.

A shallow copy means that C++ copies each member of the class individually using the assignment operator. This is also known as a member wise copy.

A deep copy duplicates the object or variable being pointed to so that the destination receives its own local copy. This way, the destination can do whatever it wants to its local copy and the object that was copied from will not be affected. Doing deep copies requires that we write our own copy constructors and overloaded assignment operators.



10.How can we check whether new operator allocates memory successfully or not?

We can include exception handling in the operator so that the exception can be caught if new failed to allocate memory.

No comments:

Post a Comment