You are on page 1of 20

C++ Paper Solution: 2018

Q1. a) Difference between structured programming and object oriented


programming.
Ans: Structured programming is a logical programming method that is considered a
precursor to object-oriented programming (OOP). Structured programming
facilitates program understanding and modification and has a top-down design
approach, where a system is divided into compositional subsystems.
OOP refers to languages that use objects in programming. Object-oriented
programming aims to implement real-world entities like inheritance, hiding,
polymorphism etc in programming. The main aim of OOP is to bind together the
data and the functions that operate on them so that no other part of the code can
access this data except that function.
b) Define class and object.
Ans: A class is a collection of similar types of objects that share common attributes
and behavior. Objects are the variables of user-defined type called class.
An object is a real-world run-time entity in OOP that has some attributes and
behavior such as person, place and vehicle. It represents user-defined data types
such as vectors, angles and programming constructs. An object contains data
variables and functions to store and manipulate the data.
c) What do you mean by data hiding.
Ans: Data hiding is an object-oriented programming technique of hiding internal
object details i.e. data members. Data hiding guarantees restricted data access to
class members & maintain object integrity.
d) Write the use of Scope Resolution operator in C++.
Ans: The :: (scope resolution) operator is used to get hidden names due to variable
scopes so that you can still use them. The scope resolution operator can be used as
both unary and binary. You can use the unary scope operator if a namespace scope
or global scope name is hidden by a particular declaration of an equivalent name
during a block or class.
e) What do you mean by polymorphism.
Ans: Polymorphism means multiple forms that allow you to use a single interface
for performing multiple actions in a program. Polymorphism helps reduce
complexity in programming by allowing you to perform common operations using
the same function name. The compiler selects the type of function that needs to be
called to perform the specific task.
f) Define templates in C++.
Ans: A template is a simple and yet very powerful tool in C++. The simple idea is to
pass data type as a parameter so that we don‘t need to write the same code for
different data types. For example, a software company may need sort() for different

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 1


C++ Paper Solution: 2018

data types. Rather than writing and maintaining the multiple codes, we can write
one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The
second keyword can always be replaced by keyword ‗class‘.

g) What are the advantages of linked list over array.


Ans: Advantages of linked lists over arrays are: Size of the list doesn't need to be
mentioned at the beginning of the program, certainly dynamic memory allocation
and deallocation. As the linked list doesn't have a size limit, we can go on adding
new nodes (elements) and increasing the size of the list to any extent.
h) Define function overloading in C++.
Ans: C++ allows you to specify more than one definition for a function name in the
same scope, which is called function overloading.
Q2. a) Discuss the important features of object oriented programming.
Explain the organization of data and function in OOP.
Ans: The basic concepts of OOP revolve around several key terms. These key terms
are:
1) Object
2) Class
3) Encapsulation
4) Abstraction
5) Inheritance
6) Polymorphism
7) Dynamic Binding
8) Reusability
9) Message Passing
10) Operator Overloading

1. Object
An object is a real-world run-time entity in OOP that has some attributes and
behavior such as person, place and vehicle. It represents user-defined data types
such as vectors, angles and programming constructs. An object contains data
variables and functions to store and manipulate the data. For example, a student
object consists of data variables such as name, rollno and marks, and functions such
as get_data(), calculate_percentage and display_data. The get_data() function reads
the data, the calculate_percentage function calculates the percentage and the
display_data function displays the student data. The functions associated with an
object are called its member functions. In an object, the data variables can only be

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 2


C++ Paper Solution: 2018

accessed by its member functions. Figure shows the data and member functions
associated with the student object.

Figure: student object


2. Class
A class is a collection of similar types of objects that share common attributes and
behavior. Objects are the variables of user-defined type called class. In an OOP
program, you create classes to develop an application. You can categorize the real
world into classes such as human being, automobiles, furniture, fruit and electrical
appliances. Each class has some properties and functions. For example, the human
being class has the properties such as height, weight, colour of eyes and colour of
hair. The functions of human being class are walking, talking, sleeping, breathing,
etc. You can take a class, Car, having properties such as model, colour and capacity.
The functions that the Car class performs are speed, average, start and stop.
In technical terms, a class consists of member variables or properties and member
functions. A class is also called abstract data type because it is only a template or
design to be used by the objects of the class. Figure shows the class, Car.

Figure: Class Structure

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 3


C++ Paper Solution: 2018

The Car class is divided into two parts—member variables or properties and
member functions. Model, colour and capacity are the properties and speed and
average are the member functions of the Car class.

3. Encapsulation
In C++, the technique of binding the data and functions together in a single unit is
called encapsulation. Encapsulation helps secure the data and functions from
outside interference as data is accessible only to the member functions of the object.
These member functions provide an interface between the data of an object and the
program. Encapsulation is also called data hiding because it protects data from
direct access. To implement this technique, the data variables and methods are
defined as private or public. The private data is accessible only to the member
functions of the class and the public data represents the information that can be
accessible to the external users of the class.
4. Abstraction
Abstraction means representing the essential features without mentioning the
background details. In C++, objects use the concept of abstraction which helps
represent only the important details related to an entity. Data can be accessed only
by the member functions of a class. Member functions of an object act as an
abstraction medium that is used to provide an interface between data and a
program.

5. Inheritance
Inheritance is the process of defining new classes by extending the properties of
other classes. The class that acquires the properties of other class is called derived
class and the class from which the properties are inherited is called base class. The
derived class shares the properties of the base class and also adds its own
characteristics to create additional features. The derived class needs to define only
those properties which are unique to it. Inheritance supports the concept of
classification. For example, a car is a part of the four-wheeler class that, in turn, is
a part of the vehicle class. It means a car has the properties of both four-wheeler
and vehicle classes. It also means that a car is a subclass of the four-wheeler class
that, in turn, is the subclass of the vehicle class. The vehicle class is the super class
of all the classes. Figure shows the concept of inheritance in OOP.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 4


C++ Paper Solution: 2018

Figure Inheritance in OOP

For example, there are three base classes and from these base classes, three classes
are derived. Each derived class contains its own unique features and the features of
a base class also. Inheritance provides the concept of reusability which means using
the existing classes to derive new classes. Using inheritance, you can add additional
properties to an existing class without modifying it.

6. Polymorphism
Polymorphism means multiple forms that allow you to use a single interface for
performing multiple actions in a program. Polymorphism helps reduce complexity in
programming by allowing you to perform common operations using the same
function name. The compiler selects the type of function that needs to be called to
perform the specific task. For example, in a shape class, polymorphism enables the
programmer to define different area methods for any geometrical shape such as
circle, rectangle or triangle. The method name, Area 0 is same but the parameters
passed in the Area 0 method are different for different shapes. Polymorphism is
widely used to implement inheritance. Figure shows an example of polymorphism.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 5


C++ Paper Solution: 2018

Figure: The Polymorphic Function

7. Dynamic Binding
Binding is the process of linking a function call to execute code. It means when a
function is called in a program, the code is attached with it during binding. Binding
is of two types—static binding and dynamic binding. Static binding means the code
to be executed in response to a function call is known at the compilation time of the
code. It means the function call is bound to its code when the program is being
compiled. Dynamic binding resolves the code associated with a given function call at
run-time. OOP supports dynamic binding. This means that OOP has the facility to
link the function call to its code at run time using virtual functions.

8. Reusability
Object-oriented programming allows reusability of a code. If you have designed a
class, any programmer can also use it in his program. You can add a new feature to
an existing class in order to make a derived class using inheritance. Figure shows
how you can implement reusability.

Figure Implementing Reusability

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 6


C++ Paper Solution: 2018

9. Message Passing
In the object-oriented programming, a program consists of objects that communicate
with each other. You create classes that consist of properties and functions. Then,
you create objects based on class definition and establish communication among
objects. The message that the objects pass among themselves is a request for
execution of a procedure. The message passing involves three things—name of the
object, name of the function and information to be sent. An object can send and
receive message until it is destroyed.

10. Operator Overloading


Operator overloading refers to a mechanism that you use to redefine operators for
different objects by using the operator keyword. You can use operator overloading to
modify the built-in operators to develop user-defined operators.

b) Explain how inline function differ from a preprocessor macro? Explain


significant advantages of inline function.
Ans: Macro is an instruction which expands at the time of its invocation. Functions
can also be defined, like macros. Similarly, the inline functions also expand at the
point of its invocation. One primary difference between inline and macro function is
that the inline functions are expanded during compilation, and the macros are
expanded when the program is processed by the preprocessor.
Advantages of inline function:-
1) It does not require function calling overhead.
2) It also save overhead of variables push/pop on the stack, while function calling.
3) It also save overhead of return call from a function.
4) It increases locality of reference by utilizing instruction cache.
5) After in-lining compiler can also apply intraprocedural optmization if specified.
This is the most important one, in this way compiler can now focus on dead code
elimination, can give more stress on branch prediction, induction variable
elimination.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 7


C++ Paper Solution: 2018

Q3. a) Write program using function template for finding the minimum
value contained in an array.
Ans:
template
T findMin(T arr[],int n)
{
int i;
T min;
min=arr[0];
for(i=0;i<n;i++)
{
if(min > arr[i])
min=arr[i];
}
return(min);
}
void main()
{
clrscr();
int iarr[]={5,4,3,2,1};
char carr[]={'z','y','c','b','a'};
double darr[]={3.3,5.5,2.2,1.1,4.4};

//calling Generic function...to find minimum value.


cout<<"Generic Function to find Minimum from Array\n\n";
cout<<"Integer Minimum is : "<<findmin(iarr,5)<<"\n";
cout<<"Character Minimum is : "<<findmin(carr,5)<<"\n";
cout<<"Double Minimum is : "<<findmin(darr,5)<<"\n";

getch();
}

b) What is operator overloading? Explain the importance of operator


overloading.
Ans: Operator overloading is a very important feature of Object Oriented
Programming. It is important because by using this facility we would be able to
create new definitions of existing operators. In other words a single operator can

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 8


C++ Paper Solution: 2018

take up several functions as desired by programmers depending on the argument


taken by the operator by using the operator overloading facility.
We can overload operators like:

We can‘t overload operators like:


Conditional operator ( ? : )
Scope resolution operator ( :: )
Class member access operator ( . )
Pointer to member operator ( . * )

Q4. a) What is abstract class? When do we use the protected visibility


specifiers to a class member?
Ans:
Abstract Class is a class which contains atleast one Pure Virtual function in
it. Abstract classes are used to provide an Interface for its
sub classes. Classes inheriting an Abstract Class must provide definition to the
pure virtual function, otherwise they will also become abstract class.
Protected variables allow access to the variables only from sub-classes and classes
within the same package. Protected variables can be useful if you want your data to
be read-only, or when you want to abstract your data. However, you can just use
private variables with getters and setters methods.

b) What is a virtual base class? Why it is important to make class virtual?


Ans: Virtual base classes are used in virtual inheritance in a way of preventing
multiple ―instances‖ of a given class appearing in an inheritance hierarchy when
using multiple inheritances.
Need for Virtual Base Classes:
Consider the situation where we have one class A .This class is A is inherited by two
other classes B and C. Both these class are inherited into another in a new
class D as shown in figure below.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 9


C++ Paper Solution: 2018

As we can see from the figure that data members/function of class A are inherited
twice to class D. One through class B and second through class C. When any data /
function member of class A is accessed by an object of class D, ambiguity arises as to
which data/function member would be called? One inherited through B or the other
inherited through C. This confuses compiler and it displays error.
class A {
public:
void show()
{
cout << "Hello form A \n";
}
};

class B : public A {
};

class C : public A {
};

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 10


C++ Paper Solution: 2018

class D : public B, public C {


};

int main()
{
D object;
object.show();
}
Compile Errors:
How to resolve this issue?

To resolve this ambiguity when class A is inherited in both class B and class C, it is
declared as virtual base class by placing a keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};
Note: virtual can be written before or after the public. Now only one copy of
data/function member will be copied to class C and class B and class A becomes the
virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class
hierarchies that use multiple inheritances. When a base class is specified as a
virtual base, it can act as an indirect base more than once without duplication of its
data members. A single copy of its data members is shared by all the base classes
that use virtual base.
class A {
public:
int a;
A() // constructor
{
a = 10;
}

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 11


C++ Paper Solution: 2018

};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;

return 0;
}
Output:
a = 10

Q5. Write a C++ program to create a class called STRING and implement
the following operations.
Display the result after every operation by overloading the operator <<

i) STRING S1=’VTU’
ii) STRING S2 = ‘JODHPUR’
iii) STRING S3= ‘S1+S2’ (use copy constructor)

#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char name[23];
public :string()
{
name[23]='\0';
PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 12
C++ Paper Solution: 2018

}
string(char s[])
{
strcpy(name,s);
}
string(string &s)
{
strcpy(name,s.name);
}
friend string operator +(string s1, string s2);
friend ostream &operator <<(ostream &out, string &s);
};
ostream &operator <<(ostream &out , string &s)
{
out <<"\t"<<s.name<<endl;
return(out);
}
string operator +(string s1, string s2)
{
string temp(s1);
//strcat(temp.name,"");
strcat(temp.name, s2.name);
return(temp);
}
void main()
{
clrscr();
string s1("hello ");
string s2("world");
string s3=s1+s2;
cout<<"\nFIRST STRING ="<<s1
<<"\nSECOND STRING ="<<s2;
cout<<"\nCONCATENATED THIRD STRING ="<<s3;
getch();
}

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 13


C++ Paper Solution: 2018

Q6. a) Write a C++ program to illustrate multiple inheritance.


Ans:
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};

// sub class derived from two base classes


class Car: public Vehicle, public FourWheeler {

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle

b) Define exception handling. Explain the use of try catch and throw for
exception handling in C++.
Ans: An exception is a problem that arises during the execution of a program. A
C++ exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 14


C++ Paper Solution: 2018

Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
 throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
 catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.
 try − A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the
code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.

Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.
Following is an example of throwing an exception when dividing by zero condition
occurs −

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 15


C++ Paper Solution: 2018

return (a/b);
}

Catching Exceptions
The catch block following the try block catches any exception. You can specify what
type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify
that a catch block should handle any type of exception that is thrown in a try block,
you must put an ellipsis, ..., between the parentheses enclosing the exception
declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch
it in catch block.
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 16


C++ Paper Solution: 2018

} catch (const char* msg) {


cerr << msg << endl;
}
return 0;
}

Q7 write short notes on following:


a) Stack
Stack is a linear data structure which follows a particular order in which the
operations are performed. The order may be LIFO(Last In First Out) or FILO(First
In Last Out).

There are many real-life examples of a stack. Consider an example of plates stacked
over one another in the canteen. The plate which is at the top is the first one to be
removed, i.e. the plate which has been placed at the bottommost position remains in
the stack for the longest period of time. So, it can be simply seen to follow
LIFO(Last In First Out)/FILO(First In Last Out) order.

Mainly the following three basic operations are performed in the stack:
 Push: Adds an item in the stack. If the stack is full, then it is said to be an
Overflow condition.
 Pop: Removes an item from the stack. The items are popped in the reversed
order in which they are pushed. If the stack is empty, then it is said to be an
Underflow condition.
 Peek or Top: Returns top element of stack.
 isEmpty: Returns true if stack is empty, else false.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 17


C++ Paper Solution: 2018

Applications of stack:
 Balancing of symbols
 Infix to Postfix /Prefix conversion
 Redo-undo features at many places like editors, photoshop.
 Forward and backward feature in web browsers
 Used in many algorithms like Tower of Hanoi, tree traversals, stock span
problem, histogram problem.
 Other applications can be Backtracking, Knight tour problem, rat in a
maze, N queen problem and sudoku solver
 In Graph Algorithms like Topological Sorting and Strongly Connected
Components

b) Queue
Queue is also an abstract data type or a linear data structure, just like stack data
structure, in which the first element is inserted from one end called the REAR(also
called tail), and the removal of existing element takes place from the other end
called as FRONT(also called head).
This makes queue as FIFO(First in First Out) data structure, which means that
element inserted first will be removed first.
Which is exactly how queue system works in real world. If you go to a ticket counter
to buy movie tickets, and are first in the queue, then you will be the first one to get
the tickets. Same is the case with Queue data structure. Data inserted first, will
leave the queue first.
The process to add an element into queue is called Enqueue and the process of
removal of an element from queue is called Dequeue.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 18


C++ Paper Solution: 2018

Basic features of Queue

1. Like stack, queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO( First in First Out ) structure.
3. Once a new element is inserted into the Queue, all the elements inserted
before the new element in the queue must be removed, to remove the new
element.
4. peek( ) function is oftenly used to return the value of first element without
dequeuing it.

Applications of Queue
Queue, as the name suggests is used whenever we need to manage any group of
objects in an order in which the first one coming in, also gets out first while the
others wait for their turn, like in the following scenarios:

1. Serving requests on a single shared resource, like a printer, CPU task


scheduling etc.
2. In real life scenario, Call Center phone systems uses Queues to hold people
calling them in an order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in
the same order as they arrive i.e First come first served.

c) Dynamic memory allocation

Memory in your C++ program is divided into two parts − the stack – All variables
declared inside the function will take up memory from the stack. The heap − this is
unused memory of the program and can be used to allocate the memory dynamically
when program runs.
We can allocate memory at run time within the heap for the variable of a given type
using a special operator in C++ which returns the address of the space allocated.
This operator is called new operator.
d) Destructor

Destructor is a member function which destructs or deletes an object.


When is destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) The function ends
(2) The program ends

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 19


C++ Paper Solution: 2018

(3) A block containing local variables ends


(4) A delete operator is called

How destructors are different from a normal member function?

Destructors have same name as the class preceded by a tilde (~). Destructors don‘t
take any argument and don‘t return anything.
class String
{
private:
char *s;
int size;
public:
String(char *); // constructor
~String(); // destructor
};

String::String(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}

String::~String()
{
delete []s;
}

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 20

You might also like