Top 50 OOPs Language Interview Questions and Answers

Top 50 OOPs Language Interview Questions and Answers

1. What is a class?

[Probably this would be the first question for a Java/c++ technical interview for freshers and sometimes for experienced as well. Try to give examples when you answer this question.]
Class defines a datatype, it’s type definition of category of thing(s). But a class actually does not define the data, it just specifies the structure of data. To use them you need to create objects out of the class. Class can be considered as a blueprint of a building, you can not stay inside blueprint of building, you need to construct building(s) out of that plan. You can create any number of buildings from the blueprint, similarly you can create any number of objects from a class.

2. What is an Object/Instance?

Object is the instance of a class, which is concrete. From the above example, we can create instance of class Vehicle as given below
Vehicle vehicleObject;
We can have different objects of the class Vehicle, for example we can have Vehicle objects with 2 tyres, 4tyres etc. Similarly different engine capacities as well.

3.What do you mean by C++ access specifiers ?
Access specifiers are used to define how the members (functions and variables) can be accessed outside the class. There are three access specifiers defined which are public, private, and protected
private:
Members declared as private are accessible only with in the same class and they cannot be accessed outside the class they are declared.
public:
Members declared as public are accessible from any where.
protected:
Members declared as protected can not be accessed from outside the class except a child class. This access specifier has significance in the context of inheritance.
4. What are the basics concepts of OOP?

Classes and Objects
Refer Questions 2 and 3 for the concepts about classes and objects
Encapsulation
Encapsulation is the mechanism by which data and associated operations/methods are bound together and thus hide the data from outside world. It’s also called data hiding. In c++, encapsulation achieved using the access specifiers (private, public and protected). Data members will be declared as private (thus protecting from direct access from outside) and public methods will be provided to access these data. Consider the below class
class Person
{
private:
int age;
public:
int getAge(){
return age;
}
int setAge(int value){
if(value > 0){
age = value;
}
}
};
In the class Person, access to the data field age is protected by declaring it as private and providing public access methods. What would have happened if there was no access methods and the field age was public? Anybody who has a Person object can set an invalid value (negative or very large value) for the age field. So by encapsulation we can preventing direct access from outside, and thus have complete control, protection and integrity of the data.
Data abstraction
Data abstraction refers to hiding the internal implementations and show only the necessary details to the outside world. In C++ data abstraction is implemented using interfaces and abstract classes.
class Stack
{
public:
virtual void push(int)=0;
virtual int pop()=0;
};

class MyStack : public Stack
{
private:
int arrayToHoldData[]; //Holds the data from stack

public:
void push(int) {
// implement push operation using array
}
int pop(){
// implement pop operation using array
}
};
In the above example, the outside world only need to know about the Stack class and its push, pop operations. Internally stack can be implemented using arrays or linked lists or queues or anything that you can think of. This means, as long as the push and pop method performs the operations work as expected, you have the freedom to change the internal implementation with out affecting other applications that use your Stack class.
Inheritance
Inheritance allows one class to inherit properties of another class. In other words, inheritance allows one class to be defined in terms of another class.
class SymmetricShape
{
public:
int getSize()
{
return size;
}
void setSize(int w)
{
size = w;
}
protected:
int size;
};

// Derived class
class Square: public SymmetricShape
{
public:
int getArea()
{
return (size * size);
}
};
In the above example, class Square inherits the properties and methods of class SymmetricShape. Inheritance is the one of the very important concepts in C++/OOP. It helps to modularise the code, improve reusability and reduces tight coupling between components of the system.

5. What is the use of volatile keyword in c++? Give an example.

Most of the times compilers will do optimization to the code to speed up the program. For example in the below code,
int a = 10;
while( a == 10){
// Do something
}
compiler may think that value of ‘a’ is not getting changed from the program and replace it with ‘while(true)’, which will result in an infinite loop. In actual scenario the value of ‘a’ may be getting updated from outside of the program.
Volatile keyword is used to tell compiler that the variable declared using volatile may be used from outside the current scope so that compiler wont apply any optimization. This matters only in case of multi-threaded applications.
In the above example if variable ‘a’ was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.

6: What are the differences between a C++ struct and C++ class?
A: The default member and base class access specifies are different. This is one of the
commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++
struct is just like a C struct, while a C++ class has inheritance, access specifes, member
functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the
class. The only differences are that a struct defaults to public member access and public base
class inheritance, and a class defaults to the private access specified and private base-class
inheritance.

7: How do you know that your class needs a virtual destructor?
A: If your class has at least one virtual function, you should make a destructor for this class
virtual. This will allow you to delete a dynamic object through a caller to a base class object. If
the destructor is non-virtual, then wrong destructor will be invoked during deletion of the
dynamic object.

8: What is encapsulation?
A: Containing and hiding Information about an object, such as internal data structures and code.
Encapsulation isolates the internal complexity of an object’s operation from the rest of the
application. For example, a client component asking for net revenue from a business object need
not know the data’s origin.

9: What is “this” pointer?
A: The this pointer is a pointer accessible only within the member functions of a class, struct, or
union type. It points to the object for which the member function is called. Static member
functions do not have a this pointer. When a nonstatic member function is called for an
object, the address of the object is passed as a hidden argument to the function. For example, the
following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object’s address is available from within the member function as the this pointer. It is legal,
though unnecessary, to use the this pointer when referring to members of the class.

10: What happens when you make call “delete this;”?
A: The code has two built-in pitfalls. First, if it executes in a member function for an extern,
static, or automatic object, the program will probably crash as soon as the delete statement
executes. There is no portable way for an object to tell that it was instantiated on the heap, so the
class cannot assert that its object is properly instantiated. Second, when an object commits
suicide this way, the using program might not know about its demise. As far as the instantiating
program is concerned, the object remains in scope and continues to exist even though the object
did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.
You should never do this. Since compiler does not know whether the object was allocated on the
stack or on the heap, “delete this” could cause a disaster.

11: What is assignment operator?
A: Default assignment operator handles assigning one object to another of the same class.
Member to member copy (shallow copy)

12: What are all the implicit member functions of the class? Or what are all the functions which
compiler implements for us if we don’t define one?
A:
(a) default ctor
(b) copy ctor
(c) assignment operator
(d) default destructor
(e) address operator
13: What is virtual function?
A: When derived class overrides the base class method by redefining the same function, then if
client wants to access redefined the method from derived class through a pointer from base class
object, then you must define this function in base class as virtual function.
class parent
{
void Show()
{
cout << “i’m parent” << endl;
}
};
class child: public parent
{
void Show()
{
cout << “i’m child” << endl;
}
};
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls parent->show()
now we goto virtual world…
class parent
{
virtual void Show()
{
cout << “i’m parent” << endl;
}
};
class child: public parent
{
void Show()
{
cout << “i’m child” << endl;
}
};
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls child->show()
Q: What is a “pure virtual” member function?
A: The abstract class whose pure virtual method has to be implemented by all the classes which
derive on these. Otherwise it would result in a compilation error. This construct should be used
when one wants to ensure that all the derived classes implement the method defined as pure
virtual in base class.

14: How virtual functions are implemented C++?
A: Virtual functions are implemented using a table of function pointers, called the vtable. There
is one entry in the table per virtual function in the class. This table is created by the constructor
of the class. When a derived class is constructed, its base class is constructed _rst which creates
the vtable. If the derived class overrides any of the base classes virtual functions, those entries in
the vtable are overwritten by the derived class constructor. This is why you should never call
virtual functions from a constructor: because the vtable entries for the object may not have
been set up by the derived class constructor yet, so you might end up calling base class
implementations of those virtual functions

15: What is pure virtual function? or what is abstract class?
A: When you de_ne only function prototype in a base class without implementation and do the
complete implementation in derived class. This base class is called abstract class and client won’t
able to instantiate an object using this base class. You can make a pure virtual function or
abstract class this way..
class Boo
{
void foo() = 0;
}
Boo MyBoo; // compilation error

16: What is Pure Virtual Function? Why and when it is used?
A: The abstract class whose pure virtual method has to be implemented by all the classes which
derive on these. Otherwise it would result in a compilation error. This construct should be used
when one wants to ensure that all the derived classes implement the method defined as pure
virtual in base class.

17: How Virtual functions call up is maintained?
A: Through Look up tables added by the compile to every class image. This also leads to
performance penalty.

18: What is a virtual destructor?
A: The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a caller
or reference to a base class, and the base-class destructor is not virtual, the derived-class
destructors are not executed, and the destruction might not be complete.

Every ordinary member function of the parent class (although such members may not always be
accessible in the derived class!)
The same initial data layout as the base class.
Doesn’t Inherit :
The base class’s constructors and destructor.
The base class’s assignment operator.
The base class’s friends

19: What is Polymorphism??
A: Polymorphism allows a client to treat di_erent objects in the same way even if they were
created from di_erent classes and exhibit di_erent behaviors. You can use implementation
inheritance to achieve polymorphism in languages such as C++ and Java. Base class object’s
pointer can invoke methods in derived class objects. You can also achieve polymorphism in C++
by function overloading and operator overloading.

20: What is problem with Runtime type identification?
A: The run time type identification comes at a cost of performance penalty. Compiler maintains
the class.
21: What is problem with Runtime type identification?
A: The run time type identification comes at a cost of performance penalty. Compiler maintains
the class.

22: What is encapsulation?
A: Containing and hiding Information about an object, such as internal data structures and code.
Encapsulation isolates the internal complexity of an object’s operation from the rest of the
application. For example, a client component asking for net revenue from a business object need
not know the data’s origin.

23: What is “this” pointer?
A: The this pointer is a pointer accessible only within the member functions of a class, struct, or
union type. It points to the object for which the member function is called. Static member
functions do not have a this pointer. When a nonstatic member function is called for an
object, the address of the object is passed as a hidden argument to the function. For example, the
following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object’s address is available from within the member function as the this pointer. It is legal,
though unnecessary, to use the this pointer when referring to members of the class.

24: What happens when you make call “delete this;”?
A: The code has two built-in pitfalls. First, if it executes in a member function for an extern,
static, or automatic object, the program will probably crash as soon as the delete statement
executes. There is no portable way for an object to tell that it was instantiated on the heap, so the
class cannot assert that its object is properly instantiated. Second, when an object commits
suicide this way, the using program might not know about its demise. As far as the instantiating
program is concerned, the object remains in scope and continues to exist even though the object
did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.
You should never do this. Since compiler does not know whether the object was allocated on the
stack or on the heap, “delete this” could cause a disaster.

25: What is assignment operator?
A: Default assignment operator handles assigning one object to another of the same class.
Member to member copy (shallow copy)

26: What are all the implicit member functions of the class? Or what are all the functions which
compiler implements for us if we don’t define one?
A:
(a) default ctor
(b) copy ctor
(c) assignment operator
(d) default destructor
(e) address operator

27: What is a container class? What are the types of container classes?
A: A container class is a class that is used to hold objects in memory or external storage. A
container class acts as a generic holder. A container class has a predefined behavior and a wellknown
interface. A container class is a supporting class whose purpose is to hide the topology
used for maintaining the list of objects in memory. When a container class contains a group of
mixed objects, the container is called a heterogeneous container; when the container is holding a
group of objects that are all the same, the container is called a homogeneous container.

28: What is Overriding?
A: To override a method, a subclass of the class that originally declared the method must declare
a method with the same name, return type (or a subclass of that return type), and same parameter
list.
The definition of the method overriding is:
· Must have same method name.
· Must have same data type.
· Must have same argument list.
Overriding a method means that replacing a method functionality in child class. To imply
overriding functionality we need parent and child classes. In the child class you define the same
method signature as one defined in the parent class.

29: How do you access the static member of a class?
A: ::

30: What is a nested class? Why can it be useful?
A: A nested class is a class enclosed within the scope of another class. For example:
// Example 1: Nested class
//
class OuterClass
{
class NestedClass
{
// …
};
// …
};
Nested classes are useful for organizing code and controlling access and dependencies. Nested
classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is
public then any code can name it as OuterClass::NestedClass. Often nested classes contain
private implementation details, and are therefore made private; in Example 1, if NestedClass
is private, then only OuterClass’s members and friends can use NestedClass. When you
instantiate as outer class, it won’t instantiate inside class.

31: What is a local class? Why can it be useful?
A: Local class is a class defined within the scope of a function _ any function, whether a
member function or a free function. For example:
// Example 2: Local class
//
int f()
{
class LocalClass
{
// …
};
// …
};
Like nested classes, local classes can be a useful tool for managing code dependencies.

32: What a derived class can add?
A: New data members
New member functions
New constructors and destructor
New friends

33: What happens when a derived-class object is created and destroyed?
A: Space is allocated (on the stack or the heap) for the full object (that is, enough space to store
the data members inherited from the base class plus the data members defined in the derived
class itself)
The base class’s constructor is called to initialize the data members inherited from the base class
The derived class’s constructor is then called to initialize the data members added in the derived
class
The derived-class object is then usable
When the object is destroyed (goes out of scope or is deleted) the derived class’s destructor is
called on the object first
Then the base class’s destructor is called on the object
Finally the allocated space for the full object is reclaimed
34: What is encapsulation?
A: Containing and hiding Information about an object, such as internal data structures and code.
Encapsulation isolates the internal complexity of an object’s operation from the rest of the
application. For example, a client component asking for net revenue from a business object need
not know the data’s origin.

35: What is “this” pointer?
A: The this pointer is a pointer accessible only within the member functions of a class, struct, or
union type. It points to the object for which the member function is called. Static member
functions do not have a this pointer. When a nonstatic member function is called for an
object, the address of the object is passed as a hidden argument to the function. For example, the
following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object’s address is available from within the member function as the this pointer. It is legal,
though unnecessary, to use the this pointer when referring to members of the class.

36: What happens when you make call “delete this;”?
A: The code has two built-in pitfalls. First, if it executes in a member function for an extern,
static, or automatic object, the program will probably crash as soon as the delete statement
executes. There is no portable way for an object to tell that it was instantiated on the heap, so the
class cannot assert that its object is properly instantiated. Second, when an object commits
suicide this way, the using program might not know about its demise. As far as the instantiating
program is concerned, the object remains in scope and continues to exist even though the object
did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.
You should never do this. Since compiler does not know whether the object was allocated on the
stack or on the heap, “delete this” could cause a disaster.

37: What is assignment operator?
A: Default assignment operator handles assigning one object to another of the same class.
Member to member copy (shallow copy)

38: What are all the implicit member functions of the class? Or what are all the functions which
compiler implements for us if we don’t define one?
A:
(a) default ctor
(b) copy ctor
(c) assignment operator
(d) default destructor
(e) address operator

39: What is a container class? What are the types of container classes?
A: A container class is a class that is used to hold objects in memory or external storage. A
container class acts as a generic holder. A container class has a predefined behavior and a wellknown
interface. A container class is a supporting class whose purpose is to hide the topology
used for maintaining the list of objects in memory. When a container class contains a group of
mixed objects, the container is called a heterogeneous container; when the container is holding a
group of objects that are all the same, the container is called a homogeneous container.

40: What is Overriding?
A: To override a method, a subclass of the class that originally declared the method must declare
a method with the same name, return type (or a subclass of that return type), and same parameter
list.
The definition of the method overriding is:
· Must have same method name.
· Must have same data type.
· Must have same argument list.
Overriding a method means that replacing a method functionality in child class. To imply
overriding functionality we need parent and child classes. In the child class you define the same
method signature as one defined in the parent class.

41: How do you access the static member of a class?
A: ::
42: What is a nested class? Why can it be useful?
A: A nested class is a class enclosed within the scope of another class. For example:
// Example 1: Nested class
//
class OuterClass
{
class NestedClass
{
// …
};
// …
};
Nested classes are useful for organizing code and controlling access and dependencies. Nested
classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is
public then any code can name it as OuterClass::NestedClass. Often nested classes contain
private implementation details, and are therefore made private; in Example 1, if NestedClass
is private, then only OuterClass’s members and friends can use NestedClass. When you
instantiate as outer class, it won’t instantiate inside class.

43: What is a local class? Why can it be useful?
A: Local class is a class defined within the scope of a function _ any function, whether a
member function or a free function. For example:
// Example 2: Local class
//
int f()
{
class LocalClass
{
// …
};
// …
};
Like nested classes, local classes can be a useful tool for managing code dependencies.

44: What a derived class can add?
A: New data members
New member functions
New constructors and destructor
New friends

45: What happens when a derived-class object is created and destroyed?
A: Space is allocated (on the stack or the heap) for the full object (that is, enough space to store
the data members inherited from the base class plus the data members defined in the derived
class itself)
The base class’s constructor is called to initialize the data members inherited from the base class
The derived class’s constructor is then called to initialize the data members added in the derived
class
The derived-class object is then usable
When the object is destroyed (goes out of scope or is deleted) the derived class’s destructor is
called on the object first
Then the base class’s destructor is called on the object
Finally the allocated space for the full object is reclaimed
46: What happens when a function throws an exception that was not specified by an exception
specification for this function?
A: Unexpected() is called, which, by default, will eventually trigger abort().

}
void f()
{
try {
…something that might throw…
}
catch (…) {
handleException();
}
}
This idiom allows a single function (handleException()) to be re-used to handle exceptions in a
number of other functions.

47: How do I throw polymorphically?
A: Sometimes people write code like:
class MyExceptionBase { };
class MyExceptionDerived : public MyExceptionBase { };
void f(MyExceptionBase& e)
{
// …
throw e;
}
void g()
{
MyExceptionDerived e;
try {
f(e);
}
catch (MyExceptionDerived& e) {
…code to handle MyExceptionDerived…
}
catch (…) {
…code to handle other exceptions…
}
}
If you try this, you might be surprised at run-time when your catch (…) clause is entered, and not
your catch (MyExceptionDerived&) clause. This happens because you didn’t throw
polymorphically. In function f(), the statement throw e; throws an object with the same type as
the static type of the expression e. In other words, it throws an instance of MyExceptionBase.
The throw statement behaves as-if the thrown object is copied, as opposed to making a “virtual
copy”.
Fortunately it’s relatively easy to correct:
class MyExceptionBase {
public:
virtual void raise();
};
void MyExceptionBase::raise()
{ throw *this; }
class MyExceptionDerived : public MyExceptionBase {
public:
virtual void raise();
};
void MyExceptionDerived::raise()
{ throw *this; }
void f(MyExceptionBase& e)
{
// …
e.raise();
}
void g()
{
MyExceptionDerived e;
try {
f(e);
}
catch (MyExceptionDerived& e) {
…code to handle MyExceptionDerived…
}
catch (…) {
…code to handle other exceptions…
}
}
Note that the throw statement has been moved into a virtual function. The statement e.raise() will
exhibit polymorphic behavior, since raise() is declared virtual and e was passed by reference. As
before, the thrown object will be of the static type of the argument in the throw statement, but
within MyExceptionDerived::raise(), that static type is MyExceptionDerived, not
MyExceptionBase.
Q: When I throw this object, how many times will it be copied?
A: Depends. Might be “zero.”
Objects that are thrown must have a publicly accessible copy-constructor. The compiler is
allowed to generate code that copies the thrown object any number of times, including zero.
However even if the compiler never actually copies the thrown object, it must make sure the
exception class’s copy constructor exists and is accessible.
48: What issue do auto_ptr objects address?
A: If you use auto_ptr objects you would not have to be concerned with heap objects not being
deleted even if the exception is thrown.

49: Can I overload operator== so it lets me compare two char[] using a string comparison?
A: No: at least one operand of any overloaded operator must be of some user-defined type (most
of the time that means a class).
But even if C++ allowed you to do this, which it doesn’t, you wouldn’t want to do it anyway
since you really should be using a std::string-like class rather than an array of char in the first
place since arrays are evi
50: Okay, that tells me the operators I can override; which operators should I override?
A: Bottom line: don’t confuse your users.
Remember the purpose of operator overloading: to reduce the cost and defect rate in code that
uses your class. If you create operators that confuse your users (because they’re cool, because
they make the code faster, because you need to prove to yourself that you can do it; doesn’t really
matter why), you’ve violated the whole reason for using operator overloading in the first place.