Professional Documents
Culture Documents
II
Object Oriented Programming
Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75
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.
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
B B
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.
-2-
Prelim Question Paper Solution
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.
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(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();
}
-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(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.
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.
#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
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.
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]
- 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
The format for declaring function templates with type parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
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).
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.
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
- 16 -