Sample Answers On OOP
Sample Answers On OOP
1. What is C++?
Ans. C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost
all aspects of the C language, while simplifying memory management and adding several features -
including a new data type known as a class (you will learn more about these later) - to allow object-oriented
programming. C++ maintains the features of C which allowed for low-level memory access but also gives
the programmer new tools to simplify memory management.
C++ used for: C++ is a powerful general-purpose programming language. It can be used to create small
programs or large applications. It can be used to make CGI scripts or console only DOS programs. C++
allows you to create programs to do almost anything you need to do. The creator of C++, has put together a
partial list of applications written in C++.
2. How do you find out if a linked-list has an end? (i.e. the list is not a cycle)
Ans. You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1
nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that
goes slower. If that is the case, then you will know the linked-list is a cycle.
3. What is a class?
A class is a user defined type or data structure declared with keyword class that has data and functions (also
called methods) as its members whose access is governed by the three access specifiers private, protected or
public (by default access to members of a class is private). A class (declared with keyword class) in C++
differs from a structure (declared with keyword struct) as by default, members are private in a class while
they are public in a structure. The private members are not accessible outside the class; they can be accessed
only through methods of the class. The public members form an interface to the class and are accessible
outside the class. Instances of these data types are known as objects and can contain member variables,
constants, member functions, and overloaded operators defined by the programmer.
4. What is an object?
An object is defined as any entity that can be utilized by using commands in a programming language.
Object can be a variable, value, data structure or a function. In object oriented environment, object is
referred to as instance of a class. Objects and classes are closely related to each other. In real world, the
objects are your TV, bicycle, desk and other entities. Methods are used to access the objects of a class. All
the interaction is done through the object’s methods. This is known as data encapsulation. The objects are
also used for data or code hiding.
A number of benefits are provided by the objects when they are used in the code:
• Ease of debugging : The object can be easily removed from the code if there is some problem due to it.
A different object can be plugged in as a replacement of the former one.
• Information hiding: The code or internal implementation is hidden from the users when interaction is
done through object’s methods.
• Reuse of code : if an object or code is written by some other programmer then you can also use that
object in your program. In this way, objects are highly reusable. This allows experts to debug, implement
task specific and complex objects that can be used in your own code.
• Modularity: You can write as well as maintain the source codes of objects in an independent manner.
This provides modular approach to programming.
5. What is the difference between an object and a class?
• An object is an instant of a class. A class is used to hold data and functions.
• When a class is declared, no memory is allocated but when the object of the class is declared,
memory is allocated. So, class is just a template.
• An object can only be created if the class is already declared otherwise it is not possible
6. What is the difference between class and structure?
Class Structure
1
Some Sample Answers for your reference
1. Class is a reference type and its object is 1. Structure is a value type that is why its object is
created on the heap memory. created on the stack memory.
2. Class can inherit the another class. 2. Structure does not support the inheritance.
3. Class can have the all types of constructor 3. Structure can only have the parameterized
and destructor. constructor. it cannot have the non-parameterized
constructor, default constructor and destructor also.
4. The member variable of class can be 4. The member variable of structure cannot be
initialized directly. initialized directly.
5. class object cannot be created without using 5. Structure object can be created without using the
the new keyword, it means we have to use it. new keyword.(optional)
Demo obj=new Demo(); Demo obj;
Class B: public A {
int b;
public:
B() {
b = 2;
}
virtual void show() {
cout << b;
}
};
int main() {
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
}
2
Some Sample Answers for your reference
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
The declaration of count declared in the main() function hides the integer named count declared in
global namespace scope. The statement ::count = 1 accesses the variable named count declared in
global namespace scope.
You can also use the class scope operator to qualify class names or class member names. If a class
member name is hidden, you can use it by qualifying it with its class name and the class scope
operator.
In the following example, the declaration of the variable X hides the class type X, but you can still
use the static class member count by qualifying it with the class type X and the scope resolution
operator.
#include <iostream>
using namespace std;
class X {
public:
static int count;
};
int main () {
int X = 0; // hides class type X
cout << X::count << endl; // use static member of class X
}
3
Some Sample Answers for your reference
FIRST
SECOND
2) In Multilevel Inheritance a Derived class can also inherited by another class Means in this
When a Derived Class again will be inherited by another Class then it creates a Multiple
Levels.
First
Second
3) Multiple Inheritances is that in which a Class inherits the features from two Base Classes
When a Derived Class takes Features from two Base Classes.
Third
First Second
Third
4) Hierarchical Inheritance is that in which a Base Class has Many Sub Classes or When a
Base Class is used or inherited by many Sub Classes.
4
Some Sample Answers for your reference
Fisrt
5) Hybrid Inheritance: This is a Mixture of two or More Inheritance and in this Inheritance a
Code May Contains two or Three types of inheritance in Single Code.
The recommendation that programmers use abstractions whenever suitable in order to avoid
duplication (usually of code) is known as the abstraction principle. The requirement that a
programming language provide suitable abstractions is also called the abstraction principle.
12. What is polymorphism? Explain with an example.
Polymorphism means the ability to take more than one form. An operation may exhibit different
behavior in different instances. The behavior depends on the types of data used in the operation. For
example, consider addition operation. For two numbers, the operation will generation sum. In case
of two strings, it will generate a third string with concatenation. Thus, polymorphism allows objects
with different internal structure to share same external interface. This means that a general class of
operations can be accessed in the same manner even though specific actions associated with each
operation may differ. There are two types of polymorphism:
Compile Time Polymorphism: Achieved using operator overloading and function overloading
Rum Time Polymorphism: Achieved using virtual functions.
Example:
#include <iostream>
using namespace std;
class Value {
protected:
int val;
public:
void set_values (int a) {
val=a;
}
};
int main () {
Cube cb;
Value * ptr = &cb;
ptr->set_values (10);
cout << "The cube of 10 is::" << cb.cube() << endl;
return 0;
}
although other alternatives also exist. It allows selective hiding of properties and methods in an
object by building an impenetrable wall to protect the code from accidental corruption.
In programming languages, encapsulation is used to refer to one of two related but distinct notions,
and sometimes to the combination thereof:
• A language mechanism for restricting access to some of the object's components.
• A language construct that facilitates the bundling of data with the methods (or other functions)
operating on that data.
Some programming language researchers and academics use the first meaning alone or in
combination with the second as a distinguishing feature of object-oriented programming, while
other programming languages which provide lexical closures view encapsulation as a feature of
the language orthogonal to object orientation.
The second definition is motivated by the fact that in many OOP languages hiding of components is
not automatic or can be overridden; thus, information hiding is defined as a separate notion by
those who prefer the second definition.
14. What do you mean by binding of data and functions?
Encapsulation is the concept to binding of data and function. The data members are allowed to
access by appropriate class function or methods. Data member cant's access from outside class.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and
data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined
types, called classes. a class can contain private, protected and public members. By default, all
items defined in a class are private. For example:
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed only by
other members of the Box class, and not by any other part of your program. This is one way
encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare
them after the public keyword. All variables or functions defined after the public specifier are
accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces encapsulation.
The ideal is to keep as many of the details of each class hidden from all other classes as possible.
15. What is function overloading and operator overloading?
Function overloading: A feature in C++ that enables several functions of the same name can be
defined with different types of parameters or different number of parameters. This feature is called
function overloading. The appropriate function will be identified by the compiler by examining the
number or the types of parameters / arguments in the overloaded function. Function overloading
reduces the investment of different function names and used to perform similar functionality by
7
Some Sample Answers for your reference
return 0;
}
Friend Class: A class can also be declared to be the friend of some other class. When we create a
friend class then all the member functions of the friend class also become the friend of the other
class. This requires the condition that the friend becoming class must be first declared or defined
(forward declaration).
#include <iostream>
using namespace std;
class MyClass {
// Declare a friend class
friend class SecondClass;
8
Some Sample Answers for your reference
public:
MyClass() : Secret(0) {}
void printMember() {
cout << Secret << endl;
}
private:
int Secret;
};
class SecondClass {
public:
void change( MyClass& yourclass, int x ) {
yourclass.Secret = x;
}
};
int main() {
MyClass my_class;
SecondClass sec_class;
my_class.printMember();
sec_class.change( my_class, 5 );
my_class.printMember();
}
Note: we declared friend class SecondClass; in the class MyClass, so we can access Secret in the
class SecondClass.
Another property of friendships is that they are not transitive: The friend of a friend is not
considered to be a friend unless explicitly specified.
17. What do you mean by inline function?
C++ inline function is powerful concept that is commonly used with classes. If a function is inline,
the compiler places a copy of the code of that function at each point where the function is called at
compile time.
Any change to an inline function could require all clients of the function to be recompiled because
compiler would need to replace all the code once again otherwise it will continue with old
functionality.
To inline a function, place the keyword inline before the function name and define the function
before any calls are made to the function. The compiler can ignore the inline qualifier in case
defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of
the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers:
#include <iostream>
using namespace std;
9
Some Sample Answers for your reference
In POP, program is divided into small In OOP, program is divided into parts called
Modularity
parts called functions. objects.
In POP, Importance is not given to data In OOP, Importance is given to the data
Importance but to functions as well as sequence of rather than procedures or functions because it
actions to be done. works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
In POP, Data can move freely from In OOP, objects can move and communicate
Data Moving
function to function in the system. with each other through member functions.
To add new data and function in POP is OOP provides an easy way to add new data
Expansion
not so easy. and function.
In POP, Most function uses Global data In OOP, data cannot move easily from
Data Access for sharing that can be accessed freely function to function, it can be kept public or
from function to function in the system. private so we can control the access of data.
POP does not have any proper way for OOP provides Data Hiding so provides more
Data Hiding
hiding data so it is less secure. security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form
10
Some Sample Answers for your reference
Example of POP are : C, VB, Example of OOP are : C++, JAVA, VB.NET,
Examples
FORTRAN, Pascal. C#.NET.
20. What is the difference between pass by reference and pass by value?
Pass by value: When you use pass-by-value, the compiler copies the value of an argument in a
calling function to a corresponding non-pointer or non-reference parameter in the called function
definition. The parameter in the called function is initialized with the value of the passed argument.
As long as the parameter has not been declared as constant, the value of the parameter can be
changed, but the changes are only performed within the scope of the called function only; they have
no effect on the value of the argument in the calling function.
for example, main passes two values: 5 and 7 to func( ). The function func( ) receives copies of
these values and accesses them by the identifiers a and b. The function func( ) changes the value of
a. When control passes back to main, the actual values of x and y are not changed.
int main(void) {
int x = 5, y = 7;
func(x, y);
cout << "In main, x = " << x << " y = " << y << endl;
return 0;
}
Pass or call by reference (C++ only): Pass-by-reference means to pass the reference of an
argument in the calling function to the corresponding formal parameter of the called function. The
called function can modify the value of the argument by using its reference passed in.
The following example shows how arguments are passed by reference. The reference parameters
are initialized with the actual arguments when the function is called.
// illustrates calling a function by reference
#include <iostream>
#using namespace std;
11
Some Sample Answers for your reference
int main(void) {
int a = 10;
int b = 20;
swapnum(a, b);
cout << "A is " << a << " and B is " << b << "\n";
return 0;
}
When the function swapnum() is called, the values of the variables a and b are exchanged because
they are passed by reference. The output is:
A is 20 and B is 10
To modify a reference that is qualified by the const qualifier, you must cast away its constness with
the const_cast operator. For example:
#include <iostream>
using namespace std;
int main() {
int a = 5;
func(a);
cout << a << endl;
}
This example outputs 6.
Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments.
The formal parameter is an alias for the argument. When the called function read or write the
formal parameter, it is actually read or write the argument itself.
The difference between pass-by-reference and pass-by-value is that modifications made to
arguments passed in by reference in the called function have effect in the calling function, whereas
modifications made to arguments passed in by value in the called function can not affect the calling
function. Use pass-by-reference if you want to modify the argument value in the calling function.
Otherwise, use pass-by-value to pass arguments.
The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or
reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if
you want to reassign the pointer. Otherwise, use constant or non-constant references to pass
arguments.
21. Why do we use virtual functions?
1. Virtual Functions are used to support " Run time Polymorphism".
2. You can make a function virtual by preceeding its declaration within the class by keyword
'virtual'.
3. When a Base Class has a virtual member function, any class that inherits from the Base Class
can redefine the function with exactly the same prototype i.e. only functionality can be
redefined, not the interface of the function.
4. A Base class pointer can be used to point to Base Class Object as well as Derived Class
Object.
12
Some Sample Answers for your reference
5. When the virtual function is called by using a Base Class Pointer, the Compiler decides at
Runtime which version of the function i.e. Base Class version or the overridden Derived Class
version is to be called. This is called Run time Polymorphism.
22. What do you mean by pure virtual functions?
A pure virtual function is a function that has the notation "= 0" in the declaration of that function.
Here is a simple example of what a pure virtual function:
Simple Example of a pure virtual function in C++
class SomeClass {
public:
virtual void pure_virtual() = 0; // a pure virtual function
// note that there is no function body
}
The pure specifier: The "= 0" portion of a pure virtual function is also known as the pure specifier,
because it’s what makes a pure virtual function “pure”. Although the pure specifier appended to the
end of the virtual function definition may look like the function is being assigned a value of 0, that
is not true. The notation "= 0" is just there to indicate that the virtual function is a pure virtual
function, and that the function has no body or definition. Also note that we named the function
“pure_virtual” – that was just to make the example easier to understand, but it certainly does not
mean that all pure virtual functions must have that name since they can have any name they want.
23. What are virtual classes?
In object-oriented programming, a virtual class is a nested inner class whose functions and
member variables can be overridden and redefined by subclasses of the outer class. Virtual classes
are analogous to virtual functions.
The run time type of a virtual class depends on the run time type of an object of the outer class.
(Just like the run time type of an object decides which virtual function should be used.)
A run time instance type of the outer class object not only decides on the polymorphic type of its
own type object, but also on a whole family tree of virtual class members.
Virtual classes solve the extensibility problem of extending data abstraction with new functions and
representations. Like virtual functions, virtual classes follow the same rules of definition,
overriding, and reference.
When a derived class inherits from a base class, it must define or override the virtual inner classes it
inherited from the base class. An object of the child class may be referred to by a reference or
pointer of the parent class type or the child class type. When the reference or pointer invoke the
virtual inner classes, the derived class's implementation will be called if the object is of the derived
class type. The type of the outer class determines the run time of the inner virtual class.
A method with an object argument has access to the object's virtual classes. The method can use the
virtual classes of its arguments to create instances and declare variables. Virtual classes of different
instances are not compatible.
Example
For example, a base class Machine could have a virtual class Parts. Subclass Car would implement
Parts differently than the subclass Bicycle, but the programmer can call any methods in the virtual
inner class Parts on any class Machine object, and get the Parts implementation of that specific
derived class.
class Machine {
void run () {}
13
Some Sample Answers for your reference
};
};
/* The inner class "Parts" of the class "Machine" may return the
number of wheels the machine has.
*/
class Parts {
int get_Wheels () {
cout << "A car has 4 wheels." << endl;
return 4;
}
string get_Fuel_Type () {
cout << "A car uses gasoline for fuel." << endl;
return "gasoline";
}
};
};
Any object of class type Machine can be accessed the same way. The programmer can ask for the
number of wheels (by calling get_Wheels()), without needing to know what kind of machine it is,
how many wheels that machine has, or all the possible types of machines there are. Functions like
get_Fuel_Type() can be added to the virtual class Parts by the derived class Car.
24. Explain about Unique Pointer and smart pointer?
Unique Pointer: Manages the storage of a pointer, providing a limited garbage-collection facility,
with little to no overhead over built-in pointers (depending on the deleter used).
These objects have the ability of taking ownership of a pointer: once they take ownership they
manage the pointed object by becoming responsible for its deletion at some point.
unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they
themselves are destroyed, or as soon as their value changes either by an assignment operation or by
an explicit call to unique_ptr::reset.
unique_ptr objects own their pointer uniquely: no other facility shall take care of deleting the object,
and thus no other managed pointer should point to its managed object, since as soon as they have to,
unique_ptr objects delete their managed object without taking into account whether other pointers
still point to the same object or not, and thus leaving any other pointers that point there as pointing
to an invalid location.
A unique_ptr object has two components:
• a stored pointer: the pointer to the object it manages. This is set on construction, can be altered
by an assignment operation or by calling member reset, and can be individually accessed for
reading using members get or release.
• a stored deleter: a callable object that takes an argument of the same type as the stored pointer
and is called to delete the managed object. It is set on construction, can be altered by an
assignment operation, and can be individually accessed using member get_deleter.
unique_ptr objects replicate a limited pointer functionality by providing access to its managed
object through operators * and -> (for individual objects), or operator [] (for array objects). For
14
Some Sample Answers for your reference
safety reasons, they do not support pointer arithmetic, and only support move assignment (disabling
copy assignments).
Smart Pointer: a smart pointer is an abstract data type that simulates a pointer while providing
additional features, such as automatic memory management or bounds checking. These additional
features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency.
Smart pointers typically keep track of the memory they point to. They may also be used to manage
other resources, such as network connections and file handles.
Misuse of pointers is a major source of bugs. Smart pointers prevent most situations of memory
leaks by making the memory deallocation automatic. More generally, they make object destruction
automatic: the object controlled by a smart pointer is automatically destroyed (finalized and then
deallocated) when the last (or only) owner of the object is destroyed, for example because the
owner is a local variable, and execution leaves the variable's scope. Smart pointers also eliminate
dangling pointers by postponing destruction until the object is no longer in use.
Several types of smart pointers exist. Some work with reference counting, others by assigning
ownership of the object to a single pointer. If a language supports automatic garbage collection (for
instance, Java or C#), then smart pointers are not needed for the reclamation and safety aspects of
memory management, but are nevertheless useful for other purposes, such as cache data structure
residence management and resource management of objects such as file handles or network sockets.
25. What are the advantages and disadvantages of inheritance?
Advantages:
One of the key benefits of inheritance is to minimize the amount of duplicate code in an application
by sharing common code amongst several subclasses. Where equivalent code exists in two related
classes, the hierarchy can usually be refactored to move the common code up to a mutual super
class. This also tends to result in a better organization of code and smaller, simpler compilation
Unit.
Inheritance can also make application code more flexible to change because classes that inherit
from a common super class can be used interchangeably. If the return type of a method is super
class
Reusability : facility to use public methods of base class without rewriting the same
Extensibility : extending the base class logic as per business logic of the derived class
Data hiding : base class can decide to keep some data private so that it cannot be altered by the
derived class
Overriding : With inheritance, we will be able to override the methods of the base class so that
meaningful implementation of the base class method can be designed in the derived class.
Disadvantages:
1. One of the main disadvantages of inheritance in Java (the same in other object-oriented
languages) is the increased time/effort it takes the program to jump through all the levels of
overloaded classes. If a given class has ten levels of abstraction above it, then it will
essentially take ten jumps to run through a function defined in each of those classes.
2. Main disadvantage of using inheritance is that the two classes (base and inherited class) get
tightly coupled. This means one cannot be used independent of each other.
3. Also with time, during maintenance adding new features both base as well as derived classes
are required to be changed. If a method signature is changed then we will be affected in both
cases (inheritance & composition)
4. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case
of using that method. Here things can get a bit complicated in case of inheritance because our
programs will still compile, but the methods of the subclass will no longer be overriding super
15
Some Sample Answers for your reference
class methods. These methods will become independent methods in their own right.
31.What is virtual constructors / destructors?
Virtual Constructors: The concept of polymorphism is by itself done in the constructor of each
class.
The constructor owns the responsibility of initializing the Vtable and vptr which actually
implements the Polymorphism technology. So constructor cannot be virtual. And it is also not
required.
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying
the delete operator to a base-class pointer to the object, the base-class destructor function (matching
the pointer type) is called on the object. There is a simple solution, declare a virtual base-class
destructor. This makes all derived-class destructors virtual even though they don’t have the same
name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by
applying the delete operator to a base-class pointer to a derived-class object, the destructor for the
appropriate class is called.
32.What is the difference between declaration and definition?
A declaration provides basic attributes of a symbol: its type and its name. A definition provides all
of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it
has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a
declaration for something in order to compile a file into an object file, expecting that the linker can
find the definition from another file. If no source file ever defines a symbol, but it is declared, you
will get errors at link time complaining about undefined symbols.
The definition contains the actual implementation.
For example
// function
void stars () {// declarator
for(int j = 10; j >= 0; j--) {//function body
cout << ”*”;
cout << endl;
}
}
sArray List
For Array memory allocated is static and For List memory allocated is dynamic and
continuous. Random.
Array: User need not have to keep in track of List: User has to keep in Track of next
next memory allocation. location where memory is allocated.
Array uses direct access of stored members, list uses sequential access for members.
16
Some Sample Answers for your reference
//With Array you have direct access to ///With the list you have to cross all previous
memory position 5 nodes in order to get the 5th node:
Object x = a[5]; // x takes directly list mylist;
// a reference to list::iterator it;
// 5th element of for(it=list.begin(); it!=list.end();
// array it++) {
if( i==5) {
x = *it;
break;
}
i++;
}
17