0% found this document useful (0 votes)
30 views17 pages

Sample Answers On OOP

Uploaded by

gurly101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views17 pages

Sample Answers On OOP

Uploaded by

gurly101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Some Sample Answers for your reference

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;

7. What are virtual functions?


Ans. A virtual function is a member function that is declared within a base class and redefined by a derived
class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual.
When a class containing virtual function is inherited, the derived class redefines the virtual function to suit
its own needs.
Base class pointer can point to derived class object. In this case, using base class pointer if we call some
function which is in both classes, then base class function is invoked. But if we want to invoke derived class
function using base class pointer, it can be achieved by defining the function as virtual in base class, this is
how virtual functions support runtime polymorphism.
Consider following program code:
Class A {
int a;
public:
A() {
a = 1;
}

virtual void show() {


cout << a;
}
};

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

Output is 2 since pA points to object of B and show() is virtual in base class A.


8. What is friend function?
In object-oriented programming, a friend function that is a "friend" of a given class is allowed
access to private and protected data in that class that it would not normally be able to as if the data
was public. Normally, a function that is defined outside of a class cannot access such information.
Declaring a function a friend of a class allows this, in languages where the concept is supported.
A friend function is declared by the class that is granting access, explicitly stating what function
from a class is allowed access. A similar concept is that of friend class. Friends should be used with
caution. Too many functions or external classes declared as friends of a class with protected or
private data may lessen the value of encapsulation of separate classes in object-oriented
programming and may indicate a problem in the overall architecture design. Generally though,
friend functions are a good thing for encapsulation, as we can keep data of a class private from all
except those who you explicitly state need it, but this does mean your classes will become tightly
coupled.
9. What is a scope resolution operator?
The :: (scope resolution) operator is used to qualify hidden names so that you can still use them.
You can use the unary scope operator if a namespace scope or global scope name is hidden by an
explicit declaration of the same name in a block or class. For example:
int count = 0;

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 X::count = 10; // define static data member

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

10. What do you mean by inheritance? Define the types of inheritance?


Inheritance: Inheritance means using the Pre-defined Code This is very Main Feature of OOP
With the advantage of Inheritance we can use any code that is previously created. With the help of
inheritance we uses the code that is previously defined but always Remember, We are only using
that code but not changing that code.
With the Advent of inheritance we are able to use pre-defined code and also able to add new code.
All the pre-defined code is reside into the form of classes if we want to use that code then we have
to inherit or extend that class.
The Class that is Pre-defined is called as Base or super Class and the class which uses the Existing
Code is known as derived or sub class
The Various Types of Inheritance those are provided by C++ are as followings:
• Single Inheritance
• Multilevel Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
In Inheritance Upper Class whose code we are actually inheriting is known as the Base or Super
Class and Class which uses the Code are known as Derived or Sub Class.
1) In Single Inheritance there is only one Super Class and Only one Sub Class Means they
have one to one Communication between them

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

Second Third Fourth

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.

11. What is abstraction?


abstraction is a technique for managing complexity of computer systems. It works by establishing
a level of complexity on which a person interacts with the system, suppressing the more complex
details below the current level. The programmer works with an idealized interface (usually well
defined) and can add additional levels of functionality that would otherwise be too complex to
handle. For example, a programmer writing code that involves numerical operations may not be
interested in the way numbers are represented in the underlying hardware (e.g. whether they're 16
bit or 32 bit integers), and where those details have been suppressed it can be said that they were
abstracted away, leaving simply numbers with which the programmer can work. In addition, a task
of sending an email message across continents would be extremely complex if you start with a
piece of optic cable and basic hardware components. By using layers of complexity that have been
created to abstract away the physical cables, network layout and presenting the programmer with a
virtual data channel, this task is manageable.
Abstraction can apply to control or to data: Control abstraction is the abstraction of actions while
data abstraction is that of data structures.
• Control abstraction involves the use of subprograms and related concepts control flows
• Data abstraction allows handling data bits in meaningful ways. For example, it is the basic
motivation behind data type.
One can view the notion of an object as a way to combine abstractions of data and code.
The same abstract definition can be used as a common interface for a family of objects with
different implementations and behaviors but which share the same meaning. The inheritance
mechanism in object-oriented programming can be used to define an abstract class as the common
interface.
5
Some Sample Answers for your reference

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;
}
};

class Cube: public Value {


public:
int cube() {
return (val*val*val);
}
};

int main () {
Cube cb;
Value * ptr = &cb;
ptr->set_values (10);
cout << "The cube of 10 is::" << cb.cube() << endl;
return 0;
}

Result: The cube of 10 is:: 1000


In the above OOPs example "Cube" is a derived class of "Value". To implement polymorphism a
pointer "ptr" is used to reference to the members of the class "Cube". This is an example for
"Compile time polymorphism." In this method object is bound to the function call only at the run
time.
13. What is encapsulation?
Encapsulation is the packing of data and functions into a single component. The features of
encapsulation are supported using classes in most object-oriented programming languages,
6
Some Sample Answers for your reference

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

more than one function.


Operator overloading: A feature in C++ that enables the redefinition of operators. This feature
operates on user defined objects. All overloaded operators provides syntactic sugar for function
calls that are equivalent. Without adding to / changing the fundamental language changes, operator
overloading provides a pleasant façade.
16. What is virtual class and friend class?
Virtual Class: When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those objects by declaring
the base class as virtual when it is being inherited. Such a base class is known as virtual base class.
This can be achieved by preceding the base class’ name with the word virtual.
Consider following example:
class A {
public:
int i;
};

class B : virtual public A {


public:
int j;
};

class C: virtual public A {


public:
int k;
};

class D: public B, public C {


public:
int sum;
};
int main() {
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”;
cout << “Value of k is : ”<< ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”;

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;

inline int Max(int x, int y) {


return (x > y) ? x : y;
}

// Main function for the program


int main( ) {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;

9
Some Sample Answers for your reference

cout << "Max (100,1010): " << Max(100,1010) << endl;


return 0;
}
When the above code is compiled and executed, it produces the following result:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
18. What do you mean by public, private, protected ,internal and friendly?
Public: The data members and methods having public as access specifier can be accessed by the
class objects created outside the class.
Protected: The data members and methods declared as protected will be accessible to the class
methods and the derived class methods only.
Private: These data members and methods will be accessible from the class methods only, not from
derived classes and not from objects created outside the class.
Internal: Some languages define internal as an access specifier which means the data member or
method is available to all the classes inside that particular assembly.
Friend: A friend class or method can access all data of a class including private and protected data.
19. What are the main differences between procedure oriented languages and object
oriented languages?

Procedure Oriented Programming Object Oriented Programming

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.

Access OOP has access specifiers named Public,


POP does not have any access specifier.
Specifiers Private, Protected, etc.

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

of Function Overloading and Operator


Overloading.

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.

// illustrates calling a function by value


#include <iostream>
using namespace std;

void func (int a, int b) {


a += b;
cout << "In func() a = " << a << " b = " << b << endl;
}

int main(void) {
int x = 5, y = 7;
func(x, y);
cout << "In main, x = " << x << " y = " << y << endl;
return 0;
}

The output of the program is:


In func, a = 12 b = 7
In main, x = 5 y = 7

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;

void swapnum(int &i, int &j) {


int temp = i;
i = j;
j = temp;
}

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;

void func(const int& x) {


int& y = const_cast < int& > (x);
++y;
}

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

virtual class Parts {

};
};

/* The inner class "Parts" of the class "Machine" may return the
number of wheels the machine has.
*/

class Car: public Machine {


void run() {
cout << "The car is running." << endl;
}

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;
}
}

33.What is the difference between an ARRAY and a LIST?

sArray List

Array is collection of homogeneous elements. List is collection of heterogeneous elements.

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++;
}

34.What is function overloading and operator overloading?


Function overloading: C++ enables several functions of the same name to be defined, as long as
these functions have different sets of parameters (at least as far as their types are concerned). This
capability is called function overloading. When an overloaded function is called, the compiler
selects the proper function by examining the number, types and order of the arguments in the call.
Function overloading is commonly used to create several functions of the same name that perform
similar tasks but on different data types.
Operator overloading: allows existing C++ operators to be redefined so that they work on objects
of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They
form a pleasant facade that doesn't add anything fundamental to the language (but they can improve
understandability and reduce maintenance costs).
35.What is the difference between an object and a class?
Classes and objects are separate but related concepts. Every object belongs to a class and every
class contains one or more related objects.
• A Class is static. All of the attributes of a class are fixed before, during, and after the execution
of a program. The attributes of a class don't change.
• The class to which an object belongs is also (usually) static. If a particular object belongs to a
certain class at the time that it is created then it almost certainly will still belong to that class
right up until the time that it is destroyed.
• An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed.
Also during that lifetime, the attributes of the object may undergo significant change.

17

You might also like