You are on page 1of 16

F.Y. B.Sc.(IT) : Sem.

II
Object Oriented Programming
Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75

Q.1 Attempt the following (any THREE) [15]


Q.1(a) Write a short note on Data abstraction and data encapsulation. [5]
Ans.: Data abstraction:
 Abstraction refers to the act of representing essential features without including the
background details or explanations.
 Classes use the concept of abstraction and are defined as a list of abstract attributes such
as size, weight and cost, and functions to operate on these attributes.
 They encapsulate all the essential properties of the objects that are to be created.
 Since the classes use the concept of data abstraction, they are known as Abstract Data
Types (ADT).

Data encapsulation:
 The wrapping up of data and functions into a single unit (called class) is known as
encapsulation.
 The data is not accessible to the outside world and only those functions which are wrapped
in the class can access it.
 These functions provide the interface between the object's data and the program.
 This insulation of the data from direct access by the program is called data hiding.

Q.1(b) Discuss procedure oriented programming paradigm. Also discuss its characteristics. [5]
Ans.: In the procedure oriented approach, the problem is viewed as the sequence of things to be
done such as reading, calculating and printing such as COBOL, fortran and c. The primary
focus is on functions. The technique of hierarchical decomposition has been used to specify
the tasks to be completed for solving a problem.

Fig.: Typical structure of procedural oriented programs.

Procedure oriented programming basically consists of writing a list of instructions for the
computer to follow, and organizing these instructions into groups known as functions. We
normally use flowcharts to organize these actions and represent the flow of control from
one action to another.

In a multi-function program, many important data items are placed as global so that they
may be accessed by all the functions. Each function may have its own local data. Global data
are more at risk to an unintentional change by a function.

Another serious drawback with the procedural approach is that we do not model real world
problems very well. This is because functions are action-oriented and do not really
corresponding to the element of the problem.

-1-
Vidyalankar : F.Y. B.Sc. (IT)  OOP

Some Characteristics exhibited by procedure-oriented programming are:


 Emphasis is on doing things (algorithms).
 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

Q.1(c) What is inheritance? State its types. [5]


Ans.: Inheritance : Inheritance is the process by which object of one class acquire the
properties of object of another class. The concept of inheritance provides the idea of code
reusability. This means that we can add additional features to an already existing class
without modifying it. Once the class has been defined and compiled it can be derived by
other classes. The old class is called the base class or parent class and the new one is called
derived class or child class. The derived class will inherit some or all features of base class
& have its own additional features.
Types of Inheritance
1) Single Inheritance 2) Multilevel Inheritance
A A

B B

3) Multiple Inheritance 4) Hierarchical Inheritance 5) Hybrid Inheritance


A B A A

C
C B D B C

D
Q.1(d) What is Polymorphism? Give example for the same. [5]
Ans.:  Polymorphism is important oops concept. It means ability to take more than one form.
 In polymorphism an operations may shows different behavior in different instances. The
behavior depends upon the type of data used in the operation. For Example, Operation of
addition for two numbers, will generate a sum. If the operands are strings, then the
operation would produce a third string by concatenation.
 The process of making an operator to show different behavior in different instance is called
as operator overloading. C++ support operator overloading.
 For Example :

The above figure shows concept of function overloading. Function overloading means using a
single function name to perform different types of tasks.

Q.1(e) Illustrate the relationship between object and class. [5]


Ans.: Objects contain data, and code to manipulate that data. The entire set of data and code of an
object can be made a user-defined data type with the help of class. Each object is associated
with the data of type class with which they are created. A class is thus a collection of objects
similar types. For examples, Mango, Apple and orange members of class fruit.

-2-
Prelim Question Paper Solution

Q.1(f) Explain static and dynamic binding. [5]


Ans.:
Basis for
Static Binding Dynamic Binding
comparison
Event Events occur at compile time are Events occur at run time are "Dynamic
Occurrence "Static Binding". Binding".
Information All information needed to call a All information need to call a function
function is known at compile time. come to know at run time.
Advantage Efficiency. Flexibility.
Time Fast execution. Slow execution.
Alternate Early Binding. Late Binding.
name
Example Overloaded function call, overloaded Virtual function in C++, overridden
operators. methods in java.

Q.2 Attempt the following (any THREE) [15]


Q.2(a) What is use of constructor? Explain with example parameterized constructor. [5]
Ans.:  Constructor are functions having same name as that of the class.
 They do not have return type. They are used to initialize variables when memory is
allocated.
 Constructor can have parameters which when present is called parameterized
constructor. When no constructor is present default constructor is automatically
created by c++.

Given example shows parametrized constructor :


class complex
{
public:
int r,i;
complex()
{
r = 0,i= 0;
}

complex(int v)
{
thir.r = v;
this.i = v;
}

complex(int r, int i)
{
this.r = r;
this.i = i;
}
};

void main()
{
complex c; //calls default one
complex c1(2); //calls second one
complex c2(3,4); //calls third one
}
Vidyalankar : F.Y. B.Sc. (IT)  OOP

Q.2(b) What is a friend function? How it can be declared? What are its characteristics? [5]
Ans.: Friend function of a class is defined outside that class' scope but it has the right to access
all private and protected members of the class. Even though the prototypes for friend
functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class


template, in which case the entire class and all of its members are friends.
Example,
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

Characteristics of friend functions :


 A friend function is not in the scope of the class, in which it has been declared as
friend.
 It cannot be called using the object of that class.
 It can be invoked like a normal function without any object.
 Unlike member functions, it cannot use the member names directly.
 It can be declared in public or private part without affecting its meaning.
 Usually, it has objects as arguments.

Q.2(c) Declare a class rectangle with data members as length and breadth, and member
functions as getdata() to read data and display() to find and display area and
perimeter of a rectangle. Also write main method to implement the class.
Ans.: #include<iostream>
#include<conio.h>
using namespace std;
class Rectangle
{
private:
int length, breadth;
public:
void getdata();
void display();
};
void Rectangle::getdata()
{
cout<<"To find the area of a Rectangle...\n";
cout<<"\tEnter length : ";
cin>>length;
cout<<"\tEnter breadth : ";
cin>>breadth;
}
void Rectangle::display()
{
cout<<"\n\tArea : "<<length*breadth;
cout<<"\n\tPerimeter : "<<2*(length+breadth);
}
int main()

-4-
Prelim Question Paper Solution

{
Rectangle r1;
r1.getdata();
r1.display();
getch();
return 0;
}

Output :
To find the area of a Rectangle...
Enter length : 2
Enter breadth : 3
Area : 6
Perimeter : 10

Q.2(d) Write a program to design a class MyCalculator with add(), mul( ) and sub( ) [5]
methods.
Ans.: class MyCalculator
{
int n, m;
public:
void get ( )
{
Cout << “\n Enter number1:”; cin >> n;
Cout << “\n Enter number2:”; cin >> m;
}
void add ( )
{
Cout << “\n sum =” << (n + m);
}
void mul ( )
{
Cout << “\n Product =” << (n * m);
}
void sub ( )
{
Cout << “\n Difference =” << (n  m);
}
};
void main ( )
{
My Calculator obj;
obj. get ( );
obj. add ( );
obj. mul ( );
obj. sub ( );
getch ( );
}

Q.2(e) Write a program to implement the concept of pointer to object. [5]


Ans.: When accessing members of a class given a pointer to an object, use the arrow () operator
instead of the dot operator.
class person
{
Vidyalankar : F.Y. B.Sc. (IT)  OOP

char name [20];


int age;
public :
void get ( )
{
Cout << “\n Enter name:”; cin >> name;
Cout << “\n Enter age:”; cin >> age;
}
void show ( )
{
cout << “\n Name :” << name;
cout << “\n Age;” << age;
}
};
void main ( )
{
person p;
person *ptr;
p. get ( );
ptr = & p;
ptr  show ( );
}

Q.2(f) Write a C++ program to create a class Bank with {acno, custname, bal} as its [5]
attributes. And implement the methods withdraw(), deposit() and show Balance().
Ans.: Class Bank {
private: intaccno; char custname[40];double bal;
public:
void withdraw()
{ Define Method // }
void deposit()
{ Define Method // }
void showBalance()
{ Define Method // }
};
void main()
{ Bank obj; obj.withdraw();
obj.deposit(); obj.showBalance();
}

Q.3 Attempt the following (any THREE) : [15]


Q.3(a) Explain the concept of function overloading with suitable example. [5]
Ans.:  Function overloading refers to creating multiple functions with the same name but
different parameter list.
 Different parameter list can be with reference to the number of parameters or the
type of parameters.
 Since, for overloaded functions the functions have same name, a function can be called
with the common name but the function that will be invoked is based on the parameter
type and number of parameters.
 This concept of function overloading is also called as function polymorphism.
 Example :
long add(long, long);
float add(float, float);
int main()

-6-
Prelim Question Paper Solution

{
long a, b, x;
float c, d, y;
cout<< "Enter two integers\n";
cin>> a >> b;
x = add(a, b);
cout<< "Sum of integers: " << x <<endl;
cout<< "Enter two floating point numbers\n";
cin>> c >> d;
y = add(c, d);
cout<< "Sum of floats: " << y <<endl;
return();
}
long add(long x, long y)
{
long sum;
sum = x + y;
return sum;
}
float add(float x, float y)
{
float sum;
sum = x + y;
return sum;
}

Q.3(b) What is pure virtual function? Explain how it is implemented. [5]


Ans.: Pure virtual Functions are virtual functions with no definition. They start with virtual
keyword and ends with = 0. Here is the syntax for a pure virtual function,
virtual void f() = 0;
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};
class Derived:public Base
{
public:
void show()
{ cout<< "Implementation of Virtual Function in Derived class"; }
};
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
 Pure Virtual functions can be given a small definition in the Abstract class, which you
want all the derived classes to have. Still you cannot create object of Abstract class.
 Also, the Pure Virtual function must be defined outside the class definition. If you will
define it inside the class definition, complier will give an error. Inline pure virtual
definition is illegal.
Vidyalankar : F.Y. B.Sc. (IT)  OOP

Q.3(c) What is method overriding? Explain the use of virtual function. [5]
Ans.: A base class member function can be inherited in the derived class, however, sometimes it
may need to be redefined according to the requirement in the derived class. This redefining
of the base class member function in the derived class is called function overriding.
Function overriding implies that a member function in a derived class has the same name as
that of the base class member function, however, has a different implementation.

Virtual functions allow us to create a list of base class pointers and call methods of any of
the derived classes without even knowing kind of derived class object.

Q.3(d) What is static member and function? State its characteristics. [5]
Ans.: Static members are associated with the class as a whole, rather than with individual
objects, however, they are accessible by any of them. The static members can be accessed
even before any object of the class is declared.
Static Member Characteristics
1. It is initialized to zero when the first object of its class is created.
2. Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
3. It is visible only within the class, but its lifetime is the entire program.
4. Static variable are normally used to maintain values common to the entire class.
5. Static variables are normally used to maintain values common to the entire class.
6. The type and the scope of each static member variable must be defined outside the
class definition.
7. They are also known as class variables.

Characteristics of static member function :


1. A static function can have access to only other static members (functions or variables)
declared in the same class.
2. A static member function can be called using the class name.

Q.3(e) Write a C++ program to add two complex numbers by overloading binary + operator. [5]
Ans.: #include<iostream>
#include<conio.h>
using namespace std;
class Complex
{
float x,y;
public:
Complex()
{
x=y=0;
}
Complex(float a, float b)
{
x=a; y=b;
}
void display()
{
cout<<x<<" + "<<y<<"i";
}
Complex operator +(Complex c)
{
Complex tmp;

-8-
Prelim Question Paper Solution

tmp.x=x+c.x;
tmp.y=y+c.y;
return tmp;
}
};
int main()
{
Complex obj1(1.5,-1.5), obj2(1,2.5),obj3;
obj3=obj1+obj2;
cout<<"\nc1 = "; obj1.display();
cout<<"\nc2 = "; obj2.display();
cout<<"\nc1+c2 = "; obj3.display();
getch();
return 0;
}

Output :
c1 = 1.5 + -1.5i
c2 = 1 + 2.5i
c1+c2 = 2.5 + 1i

Q.3(f) What is this pointer? Write a C++ program to demonstrate use of this pointer. [5]
Ans.: this pointer holds the address of current object, in simple words you can say that this
pointer points to the current object of the class.

Following are the situations where ‘this’ pointer is used :


1. When local variable’s name is same as member’s name
2. To return reference to the calling object

#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
obj1.setX(10).setY(20);
obj1.print();
return 0;
}

Output :
x = 10
y = 20
Vidyalankar : F.Y. B.Sc. (IT)  OOP

Q.4 Attempt the following (any THREE) [15]


Q.4(a) Can private members of a base class are inheritable? Justify. [5]
Ans.:  Private members are members which are accessed only with the class in which it is
defined.
 They are not exposed to outside world hence they cannot be accessed even from the
object of the class.
 Since they are internal they cannot be inherited.

Q.4(b) What is exception? Explain exceptions handling mechanism? [5]


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.

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.

try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}

Q.4(c) What happen when raised exception is not caught by catch block? Explain with [5]
suitable example.
Ans.: The catch block simply gives you the opportunity to handle a thrown exception. The catch
block itself does nothing other than to catch a specific exception when it is thrown.

But once caught, it is up to the programmer to decide how it is handled by providing specific
code to deal with the exception.

An exception is not an error unless it is unhandled, which effectively renders your program
undefined.

So its a good idea to include a general exception handler near the top of the call stack to report
the exception and provide a graceful fallback. The alternative is to allow the operating system
to handle the exception which inevitably results in your program terminating unexpectedly,
which is never a good thing.

#include <iostream>
void function1()
{
throw 1;
}

- 10 -
Prelim Question Paper Solution

void function2()
{
function1();
}
int main()
{
try
{
function2();
}
catch(...)
{
:cout << "caught!";
return 0;
}
return 0;
}

Output: caught!

Q.4(d) Write a C++ program to show use of multiple catch statements. [5]
Ans.: #include <iostream>
using namespace std;
// Different type of exception can be caught.
void Xhandler(int test)
{
try
{
if (test) throw test;
else throw "Value is zero";
}
catch(int i)
{
cout << "Caught one! Ex. #: " << i << "\n";
}
catch(char *str)
{
cout << "Caught a string: " << str << "\n";
}
}
int main( )
{
cout << "start";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "end";
return 0;
}
Vidyalankar : F.Y. B.Sc. (IT)  OOP

Output :
start
Caught one! Ex. #: 1
Caught one! Ex. #: 2
Caught one! Ex. #: 3
end

Q.4(e) What are access specifiers? Explain the use of each. [5]
Ans.: Access specifiers defines the access control rules.
These access specifiers are used to set boundaries for availability of members of class be
if data members or member functions.

There are 3 access specifiers :


1. Public 2. Private 3. Protected

1. Public : All the class under members declared under public will be available to everyone.
The data members and member functions declared public can be accessed by other
classes too.
2. Private : Private means that no one can access the class members declared private
outside that class. If someone tries to access the private member, they will get a
compile time error. By default, class variables & member functions are private.
3. Protected : Protected makes class member inaccessible outside the class. But they can
be accessed by any subclass of that class.

Q.4(f) Write a C++ program to implement the following hierarchy of inheritance. [5]

Ans.: Class Lion


{
public
int size1;
void getsize1()
{
cout<< “enter the value of Lion size : ”;
un >> size;
}
};
Class Tiger
{
public:
int size 2;
void getside2()
{
cout<< “enter the value of Tiger size : ”;
un >> size;
}
};
Class Animal : public Lion , public Tiger
{
public :
void sum( )
{
cout << “sum of sizes of both animal = ” << size 1 + size 2;

- 12 -
Prelim Question Paper Solution

}
};
int main()
{
Animal obj 1;
obj1.getsize1( );
obj.getsize2( );
obj1.sum();
return 0;
}

Output :
Enter the value of Lion size
100
Enter the value of Tiger size
150
Sum of sizes of both animal
250

Q.5 Attempt the following (any THREE) [15]


Q.5(a) What is a function template? Write a C++ program to demonstrate the use of [5]
function templates?
Ans.: Function templates are special functions that can operate with generic types. This allows us
to create a function template whose functionality can be adapted to more than one type or
class without repeating the entire code for each type.

The format for declaring function templates with type parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;

Example, function template for swap function.


#include<iostream>
using namespace std;
template<class type1>
void doSwap(type1 &a, type1 &b)
{
type1 t=a;
a=b;
b=t;
}
void main()
{
int x1,y1;
float x2,y2;
cout<<"\nEnter two integers...\n";
cin>>x1>>y1;
cout<<"\nEnter two float numbers...\n";
cin>>x2>>y2;
cout<<"\n\nIntegers Before swapping x1= "<<x1<<" and y1= "<<y1;
doSwap<int>(x1,y1);
cout<<"\nIntegers After swapping x1= "<<x1<<" and y1= "<<y1;
cout<<"\n\nfloats Before swapping x2= "<<x2<<" and y2= "<<y2;
doSwap<float>(x2,y2);
cout<<"\nfloats After swapping x2= "<<x2<<" and y2= "<<y2;
Vidyalankar : F.Y. B.Sc. (IT)  OOP

cout<<endl;
system("pause");
}

Q.5(b) What is file? Write down the steps for manipulating files in C++. [5]
Ans.: File Handling concept in C++ language is used for store a data permanently in computer.
Using file handling we can store our data in Secondary memory (Hard disk).

For achieving file handling in C++ we need follow following steps :


 Naming a file
 Opening a file
 Reading data from file
 Writing data into file
 Closing a file

Functions use in File Handling :


Function Operation
open() To create a file
close() To close an existing file
get() Read a single character from a file
put() write a single character in file.
read() Read data from file
write() Write data into file.

Q.5(c) What are file operations? Explain different modes of files. [5]
Ans.: File operations :
1. Assigning a name to the file : Every file has a name to identify in its directory.
2. Opening the file : It may involve opening a new file if it does not exist, or opening an
existing file.
3. File Processing : A file is opened for different purposes that is, for reading, for writing,
for both reading and writing, or to append some data, or delete some data, or modify
some data. The purpose of opening a file is called mode of file or file open mode.
4. Deleting Errors : Sometime, few operations are not carried out due to some cause. This
cause must be determined and rectified.
5. Closing the file : After processing, the file must be closed.

Different modes of file :


Mode Description
1. ios :: app : Mode for appending at the end of the file.
2. ios :: ate : Mode for opening at the end of the file.
3. ios :: binary : Mode for opening as binary file.
4. ios :: in : Open for reading mode.
5. ios :: out : Open the file for writing.
6. ios :: trunk : Delete the contents of the file if exists.

Q.5(d) Write a program to copy the content from file1 to file2. [5]
Ans.:  include < fstream.h>
void main ( )
{
char data [80];
ifstream fread (“Student.txt”);
ofstream fwrite (“file2.txt”);
while (fread)

- 14 -
Prelim Question Paper Solution

{
fread.getline (data, 80);
fwrite << data << endl;
}
fread.close ( );
fwrite.close ( );
}

Q.5(e) Write a program to read data from user and write to the file. [5]
Ans.:  include < fstream.h>
void main ( )
{
char data [80];
of stream fwrite (“student.txt”);
fwrite << “RollNo \t Name \t \t percentage” << endl;
fwrite << “A101 \t sagar \t \t 89.95% “<<endl;
fwrite << “A102 \t sanjeela \t \t 92%” << endl;
fwrite.close ( );
if stream fread (“Student.txt”);
While (fread)
{
fread.getline(data, 80);
cout << data << endl;
}
Fread close ( );
}

Q.5(f) Write a C++ program to implement the concept of class template. [5]
Ans.: #include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class Stack {
private:
vector<T>elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const { // return true if empty.
return elems.empty();
}
};
template <class T>
void Stack<T>::push (T const&elem) {
// append copy of passed element
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop () {
if (elems.empty()) {
Vidyalankar : F.Y. B.Sc. (IT)  OOP

throw out_of_range("Stack<>::pop(): empty stack");


}
// remove last element
elems.pop_back();
}
template <class T>
T Stack<T>::top () const {
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}
int main() {
try {
Stack<int>intStack; // stack of ints
Stack<string>stringStack; // stack of strings
// manipulate int stack
intStack.push(7);
cout<<intStack.top() <<endl; // manipulate string stack
stringStack.push("hello");
cout<<stringStack.top() <<std: :endl;
stringStack.pop();
stringStack.pop();
} catch (exception const& ex) {
cerr<< "Exception: " <<ex.what() <<endl;
return -1;
}
}



- 16 -

You might also like