Oop Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Laboratory Manual for

EC-404– Object Oriented Programming

B. Tech.

SEM. IV (EC)

Department of Electronics & Communication


Faculty of Technology
Dharmsinh Desai University
Nadiad
TABLE OF CONTENTS

PART – I LABORATORY MANUAL

Sr No. Title Page No.


1. Starting with C++ 1
2. Classes and Objects 3
3. Constructors & Destructors 5
4. Function Overloading 8
5. Operator Overloading 10
6. Type Conversion 12
7. Inheritance 14
8. Polymorphism 16
9. File Management in C++ 18
10. Exception Handling 20
11. Templates 22

PART – II SESSIONAL QUESTION PAPERS


PART I

LABORATORY MANUAL
LAB 1

STARTING WITH C++

OBJECTIVES:
(i) To gain experience with
a) Integer and floating-point numbers.
b) Writing arithmetic expressions in C++.
c) Understand nested branches and loops.
d) Programming loops with the for and do/while statements.

Using the ANSI C++ standard string type to define and manipulate character strings Writing
simple programs that read numbers and text, process the input and display the results.

SAMPLE PROGRAM:

Write a program in C++ to count total number of digits in an input number.

#include <iostream.h>
void main( )
{
int input;
cout << "Input an integer: ";
cin >> input;
int d = 1;
int temp = input;
while (temp > 9)
{
temp = temp / 10;
d++;
}
cout << input << " expressed in " << d << " digits" << "\n";
}

EXERCISES:

(1) Write a program to add a list of integers. The program should add the numbers until a 0 is
entered. Display the sum.
(2) Write a program for converting temperature from one scale to another. It should have an
option of converting from oC to oF and from oF to oC.
(3) Write a program to display multiplication tables of numbers from 20 to 30.
(4) Write a program to find the factors of any number. Also find the prime factors of that
number.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 1
(5) Write a program to convert a decimal number into its Roman equivalent. (1 – I; 5 – V; 10 –
X; 50 – L; 100 – C)
(6) Write a program to display the following triangle:
1
23
456
7 8 9 10
(7) Write a program to find the roots of a quadratic equation. The program should check
whether the equation is quadratic or not. It should also check whether the roots are real or
not. In all cases (real or complex roots) it should display the roots of the equation. Display
complex roots in the form a + ib or a – ib.
(8) Write a function to find the area of a sector. The values of radius and angle should be
passed as parameters to the function. The function should return the value of the area. All
values should be floating point numbers.
(9) Write a program to input a string and display it in reverse order.
(10) Write a function to find the factorial of any number. Display a table of factorials of numbers
from 1 to 20.
(11) Write a program to display a table of cosine, sine, tangent, secant, cosecant and
cotangent functions for different angles. Check for divide by zero condition.
(12) Write a program to convert a decimal number into its binary equivalent.
(13) Write a program to plot a graph of y = x2 function.
(14) Write a program to display the calendar for any month in the year 2002. January 1, 2002 is
Tuesday.
(15) Bubbles sort an array of 10 integers. Arrange them in descending order.
(16) Write a menu driven program that can do the following operations:
Addition, subtraction and multiplication of two 3X3 matrices.
(17) Define a structure Class. It should contain the name, age, marks in 3 subjects and overall
percentage of a student. Generate a list of 5 students. Sort and print them according to:
a. Alphabetical order of their name.
b. Overall percentage.
(18) Define a structure book_shop. It should contain the name of the book, name of the author,
number of copies available, price of the book and a Book ID No. Create a list of 5 such
books. Write a function to search for a book using the name of the book. Ask the user for
the number of copies he wants. Calculate the cost. If sufficient copies are not available,
display appropriate message. Write a function to update the database after each
purchase.
(19) Write a function to exchange the values of two variables. Use pass by reference method to
exchange the data.
(20) Write a function that receives a sorted array of integers and an integer value, and inserts
the value in its correct place.
(21) Write a program to display the Fibonacci sequence.
(22) Write a program to generate a list of prime numbers from 1 to N, where N is the number
inputted in the program.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 2
LAB 2

CLASSES AND OBJECTS

OBJECTIVES:
(i) To introduce class and objects.
(ii) To write simple programs using classes and objects

SAMPLE PROGRAM:

Define a class Cube that should contain its dimensions and the appropriate functions to get and
display data. The class should include a function to calculate the volume of the cube using the
cube dimensions.

#include “iostream”
using namespace std;
class Cube {
private:
float height;
float width;
float length;
public:
void SetData(float h, float w, float l)
{
height = h;
width = w;
length = l;
}
void GetData( )
{
cout << "Enter Height: ";
cin >> height;
cout << "Enter Width: ";
cin >> width;
cout << "Enter Length: ";
cin >> length;
}
void ShowData( )
{
cout << "Dimensions of the objects are:\n";
cout << "Height: "<<height<<",Width: "<<width<<", Length: "<<length ;
}
void Volume( )

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 3
{
cout << "\nVolume of the cube is: " << height * width * length << endl;
}
};
int main( )
{
Cube c1;
c1.SetData(12.3, 23.4, 34.5);
cout << "Object c1: " << endl;
c1.ShowData( );
//cout << c1.height; //This statement will show error. Private data not accessible.
c1.Volume( );
Cube c2;
cout << "\nEnter the content of object c2: " << endl;
c2.GetData( );
cout << "Object c2: " << endl;
c2.ShowData( );
c2.Volume( );
return 0;
}

MODIFICATIONS:

(1) Modify the above program to write all the function definitions outside the class.
(2) Add a function, which displays a menu having the options to find the surface area and the
volume of the cube. Write another function to calculate the surface area of the cube from
the input dimensions. The menu itself should call the appropriate function to calculate
volume or surface area.

EXERCISE:

(1) Imagine an experiment in which you have to observe the performance of charging of a
capacitor. You have to give the charging voltage, the value of the capacitance and
resistance as inputs. The output should be a table showing the voltage across the
capacitor w.r.t to time. Remember that the capacitor will be completely charged at time
equal to the 5 times of time constant τ. So time should be varied from 0 till 5τ in suitable
steps. Design a suitable class Experiment having appropriate functions to input the data,
calculate the voltage and display the output.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 4
LAB 3

CONSTRUCTOR

OBJECTIVES:
(i) To understand the process of creating an objects
(ii) To study the initialization of data members through constructors.

SAMPLE PROGRAM:

The sample program demonstrates the working of constructor in class. The program stores
distance two points from the one reference point and calculate the distance between them.

#include<iostream>
#include<stdlib.h>
using namespace std;
class Distance
{
private:
int mts;
int cms;
public:
Distance ( )
{
mts =0; cms=0;
}
void GetData( );
void Display( );
void CalDist(Distance, Distance);
};
void Distance::GetData( )
{
cout << “\nEnter Distance in mts: ”;
cin >>mts;
cout << “Enter Distance in cms: ”;
cin >> cms;
}
void Distance::Display( )
{
while(cms >=100)
{
mts++;
cms- =100;

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 5
}
cout <<”Meters:”<<mts<<”\t Centimeters:”<<cms<<endl;
}
void Distance::CalDist(Distance d1, Distance d2)
{
mts = abs(d1.mts – d2.mts);
cms = abs(d1.cms-d2.cms);
}
int main( )
{
Distance dist1, dist2,dist3;
dist1.GetData( );
dist2.GetData( );
dist3.CalDist(dist1,dist2);
cout << “Content of dist1 = ”<<dist1.Display( );
cout << “Content of dist2 = ”<<dist2.Display( );
cout << “Content of dist3 = ”<<dist3.Display( );
return 0;
}

MODIFICATIONS:

(1) Modify the above program to overload the Constructor to initialize new objects by passing
parameters in two ways :
Distance in mts and cms is passed.
Only distance in mts is passed.
Only distance in cns is passed.
Remove GetData( ) if it has become redundant.
(2) Modify the CalDist( ) to return the resulting distance. Modify each Constructor such that it
also display the number of times it is called.

EXERCISE:

(1) Create a class Patient which has the following content: Name of Patient, Age, Sex, Ward
Number, and Bed Number.Each ward has 2 beds, both of which should be filled before
moving on to the next ward. Ward number and Bed number should be automatically
initialized using the default constructor for each new patient. Use another constructor to
initialize them using the explicit values passed as arguments.

Write a member function to do following:


To input details of patient
To modify a patient’s detail
To display patient’s detail

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 6
Write a program which creates an array of 5 patients. Also creates the menu which asks
the user to choose from following tasks:
Enter the patient detail
Change the patient detail
Display the patient detail
Sort the array of patients according to their ages.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 7
LAB 4

FUNCTIONS OVERLOADING

OBJECTIVES:
(i) To understand the concept of function overloading.

SAMPLE PROGRAM:

A sample program finds the volume of different shapes by using the concept of function
overloading.

#include <iostream>
using namespace std;
class Shape
{
public:
int volume (int); //To find volume of sphere
double volume (double, int); //To find volume of cylinder
long volume (long, int, int); //To find volume of cube
};
int Shape :: volume(int s)
{
return (s*s*s);
}
double Shape :: volume(double r,int h)
{
return(3.14159*r*r*h);
}
long Shape :: volume(long l,int b,int h)
{
return(l*b*h);
}
void main( )
{
Shape sphere, cylinder, cube;
cout<<"VOLUME OF SPHERE => "<<sphere.volume(10)<<endl;
cout<<"VOLUME OF CYLINDER => "<<cylinder.volume(2.5,8)<<endl;
cout<<"VOLUME OF CUBE => "<<cube.volume(100L,75,15);
}

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 8
MODIFICATION:

(1) Modify the above program to include a function Area which can calculate the surface
areas of a sphere, a cylinder or a cube using the concept of function overloading.

EXERCISE:

(1) Create a class Telephone Directory which has following information: Telephone number,
Name of subscriber and Address. Write a member function to perform the following tasks:
a) To input the details of subscriber
b) To print the details of subscriber according to inquiry generated from user. Inquiry is
either based on telephone number or name of subscriber.
c) To modify the details of a particular subscriber, Modification is based on name of
subscriber, if more than one match is found; it has to ask another field. Based on
second field, it will modify the details.
Write a program for 10 subscribers, which will creates the menu for following tasks:
a) Enter the details of subscriber
b) Inquiry for subscriber
c) Modify the detail of subscriber

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 9
LAB 5

OPERATOR OVERLOADING

OBJECTIVE:
(i) To understand the concept of operator overloading.

SAMPLE PROGRAM:

A sample program finds the volume of different shapes by using the concept of function
overloading.

#include <iostream>
#include<string.h>
using namespace std;
class String
{
char Name[25];
public: String(char *name)
{
strcpy(Name,name);
}
int operator == (String);
};
int String::operator == (String S1) {
if(strcmp(Name,S1.Name))
return 0;
else
return 1;
}
int main ( )
{
String Str1("There");
String Str2("There");
if(Str1 == Str2)
cout<<"Both strings are equal"<<endl;
else
cout<<"Strings are not equal"<<endl;
return 0;
}
MODIFICATION:

(1) Modify the above program to overload + operator to concatenate the two strings using
operator overloading.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 10
EXERCISE:

(1) Use the class definition described in lab3 for the Distance class. Overload -- operator to
perform following operation in which it subtracts 1 from meters member and check that
distance should not be negative.
dist1--;
Function should allow to use the result in other operation like dist2 = dist1--; and also write
modified function which differentiate postfix and prefix notation.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 11
LAB 6

TYPE CONVERSION

OBJECTIVES:
(i) To understand the concept of Type Conversion.

SAMPLE PROGRAM:

Following program demonstrates how to convert basic types to objects and vice versa. Here
class Time encapsulates time of one particular time zone.

#include<iostream>
using namespace std;

class Time
{
int hrs, mins, secs;
public:
Time( )
{
hrs = mins = secs = 0;
cout << “Default Constructor called.”;
}
Time(int h, int m, int s)
{
hrs = h; mins = m; secs = s;
cout << “Three argument Constructor called.”;
}
Time(int s) //One argument constructor to convert from basic to user defined type.
{
hrs = s / 3600;
s %= 3600;
mins = s / 60;
secs = s % 60;
cout << “One argument Constructor called.”;
}
operator int( ) //Conversion function to convert from user defined to basic type.
{
int s = (hrs * 3600) + (mins * 60) + secs;
return s;
}
void getTime();

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 12
void showTime();
};
void Time :: getTime()
{
cout<<"Enter hours: "; cin >> hrs;
cout<<”Enter minutes: ”; cin >> mins;
cout<<”Enter seconds: ”; cin >> secs;
}
void Time :: showTime( )
{
cout << hrs << “ : ” << mins << “ : ” << secs << endl;
}

void main( ){
Time t1 = 3800;
cout << “Time t1: ”;
t1.showTime( );
Time t2(10, 20, 40);
cout << “Time t2: ”;
t2.showTime( );
int s = t2; //Implicit casting
// int s = int(t2); //Explicit casting
cout << “Time t2 in seconds:” << s;
}

EXERCISE:

(1) Create two classes Degree and Radian to store two angles in degree and in radian
respectively. Assign object of one class with other. Do appropriate conversion for this
assignment. Declare, perform operation and show the results in main. Show both possible
way of conversion.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 13
LAB 7

INHERITANCE

OBJECTIVES:
(i) To understand the concept of Inheritance.
(ii) To write programs using Inheritance.

SAMPLE PROGRAM:

#include <iostream>
using namsespace std;
class X
{
protected:
int a;
public:
X(void);
};
class Z : public X
{
public:
Z(void);
int make_aa(void);
};
X::X(void)
{
a=10; cout<<"initializing X\n";
}
Z::Z(void)
{
cout<<"initializing Z\n";
}
int Z::make_aa(void){ return a*a; }
main(void)
{
Z i;
cout<<i.make_aa( );
return 0;
}

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 14
MODIFICATIONS:

(1) Modify the above program to include one more data member int b and write a member
function for multiplication of a and b in class Z.
(2) Modify the above modification program to include a constructor in class Z to initialize a
and b.

EXERCISES:

(1) Design a class Student with data members: Name, ID and Semester. Derive another class
Sessional with an array of 5 integers to store sessional marks of 5 subjects. Derive a class
External with an array of 5 integers to store the marks of 5 subjects. Write suitable
member functions to initialize the data members of each class and produce the marksheet
of the student containing the marks of sessional and external examination with total marks
as well.
(2) What should be the total memory requirement for the object of class Z and External? How
can it be verified in the program?
(3) Will the sample program work correctly, if the access specifier is made private with X while
deriving Z? Explain your answer.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 15
LAB 8

POLYMORPHISM
OBJECTIVES:
(i) To understand the concept of Polymorphism.
(ii) To write programs using Polymorphism.

SAMPLE PROGRAM:
#include <iostream>
using namespace std;
class convert {
protected:
double val1; // initial value
double val2; // converted value
public:
convert(double i)
{
val1 = i;
}
double getconv( )
{ return val2; }
double getinit( )
{ return val1; }
virtual void compute( ) = 0;
};
// Liters to gallons.
class l_to_g : public convert {
public:
l_to_g(double i) : convert(i) { }
void compute( )
{
val2 = val1 / 3.7854;
}
};
// Fahrenheit to Celsius
class f_to_c : public convert {
public:
f_to_c(double i) : convert(i) { }
void compute( )
{
val2 = (val1-32) / 1.8;
}
};

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 16
int main( ) {
convert *p; // pointer to base class
l_to_g lgob(4);
f_to_c fcob(70);
// use virtual function mechanism to convert
p = &lgob;
cout << p->getinit( ) << " liters is ";
p->compute( );
cout << p->getconv( ) << " gallons\n"; // l_to_g
p = &fcob;
cout << p->getinit( ) << " in Fahrenheit is ";
p->compute( );
cout << p->getconv( ) << " Celsius\n"; // f_to_c
return 0;
}

MODIFICATION:

(1) Modify the above program to include the class f_to_m which will convert the feet in to
meters.

EXERCISE:

(1) Create a class called Number has one data member of type integer. There two member
function Setvalue( ) which will set the value of data member and show( ) to display the
value. Drive a class HexType, DecimalType and OctType from base class which redefined
the show() will display the value of data member of base class in respective number base.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 17
LAB 9

FILE MANAGEMENT IN C++


OBJECTIVES:
(i) To understand the concept of File Management in C++.
(ii) To write programs using File Operations in C++.

SAMPLE PROGRAM:

#include <iostream>
#include <fstream>
#include <cstring>
#include<iomanip>

using namespace std;

class Inventory {
char name[20];
int code;
float cost;
public:
Inventory ( ) { };
Inventory(char *n, int cd,float ct){
strcpy(name, n);
code = cd;
cost = ct;
}

void getdata( ) {
cout<<"Enter name:";
cin>>name;
cout<<"Enter code:";
cin>>code;
cout<<"Enter cost:";
cin>>cost;
}

void putdata( ) {
cout<<setw(10)<<name<<endl;
cout<<setw(10)<<code<<endl;
cout<<setw(10)<<cost<<endl;
}
};

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 18
int main( ) {
Inventory item,item1;
char c;
fstream infile("file.txt", ios::in | ios::out | ios::binary);
do {
cout << "1. Enter numbers\n";
cout << "2. Display numbers\n";
cout << "3. Quit\n";
cout << "\nEnter a choice: ";
cin >> c;

switch(c) {
case '1':
item.getdata( );
infile.write((char *)&item,sizeof(item));
break;
case '2':
infile.seekg(0,ios::beg);
while(infile.read((char *)&item1,sizeof(item1)))
{
item1.putdata( );
}
cout << endl;
break;
case '3':
infile.close( );

}
} while(c !='3');
return 0;
}

MODIFICATION:

(1) Modify the above program that modifies the detail of items that is already present in file
and also add new item information in file.

EXERCISE:

(1) Write a program to split the content of file that is created by sample program into two files.
One file has name of all items present in stock.txt and Second file has cost of all item
present in stock.txt using command line argument.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 19
LAB 10

EXCEPTION HANDLING

OBJECTIVES:
(i) To understand the concept of Exception Handling.
(ii) To write programs using Exception Handling.
(iii) To understand the concept of Re-throw.

SAMPLE PROGRAM:

#include<iostream>
using namespace std;
class Dummy{
private:
int n;
public:
Dummy(){}
Dummy(int n){
n=m;
}
int divide(int a){
if(a==0)
throw a;
cout<<”\n returning from divide”<<endl;
return (n/a);
}
};

int main( ){
Dummy d1;
int b,c;
bool flag;
d1=5;
flag=true;
while(flag){
cout<<”\n enter b\n”;
cin>>b;
try{
c=d1.divide(b);
flag=false;
}
catch(int x){

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 20
cout<<”attempt of division by zero\n”;
cout<<”check your input again\n”;
}
}
cout<<”\nans=”<<c<<endl;
return 0;
}

MODIFICATION:

(1) Understand the above program thoroughly and modify it in such a way that the user is
given maximum three attempts of division to re execute the code after an attempt of
division by zero. The program should exit otherwise.
Hint: Use rethrowing of exception.

EXERCISE:

(1) Modify the above modified program further so as to display a suitable warning message
before exiting the main due to an exception that is rethrown.
Hint: Use your own terminate ( )

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 21
LAB 11

TEMPLATES

OBJECTIVES:
(i) To understand the concept of Template.
(ii) To learn how to create template class.

SAMPLE PROGRAM:

#include<iostream>
using namespace std;
template <class T>
void swap1 (T & p, T& q)
{
T temp;
temp = p;
p = q;
q =temp;
}
int main( )
{
int a,b;
float x,y;

cout<<"Enter two integers:";


cin>>a>>b;
cout<<"Enter two floats:";
cin>>x>>y;

swap1(a,b);
swap1(x,y);

cout<<"Value of integers after swapping:";


cout<<a<<"\t"<<b;
cout<<endl;
cout<<"Value of floats after swapping:";
cout<<x<<"\t"<<y;
cout<<endl;

return 0;
}

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 22
MODIFICATION:

(1) Modify the above program to demonstrate the use of explicit specialization of a template
function swap1( ).

EXERCISES:

(1) Define a template class Array that will have three member functions given below:
a. sort( ) that will sort the elements in ascending order.
b. reverse( ) that will reverse the content of an array and
c. safe( ) that will check the size of array; if size is exceeded terminate the program
otherwise perform the above two task.
(2) Rewrite the above program in such a way that it has one non-type argument in template
function well as default arguments to template function.

Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 23
PART II

SESSIONAL QUESTION PAPERS


DHARMSINH DESAI UNIVERSITY, NADIAD
FACULTY OF TECHNOLOGY
B.TECH. SEMESTER IV [ELECTRONICS & COMMUNICATION]
SUBJECT: (EC404) OBJECT ORIENTED PROGRAMMING
Examination : First Sessional Examination Seat No. : ___________
Date : 22/01/2016 Day :Friday
Time : 11:00 to 12:15 Max. Marks : 36
INSTRUCTIONS:
1. Figures to the right indicate maximum marks for that question.
2. The symbols used carry their usual meanings.
3. Assume suitable data, if required & mention them clearly.
4. Draw neat sketches wherever necessary.

Q.1 (A)Choose the most appropriate answer. [3]


(1) A constant member function can modify
a) private data member c) mutable private data member
b) public data member d) none
(2) Overloaded functions
a) are a group of functions with the same name.
b) all have the same number of and types of arguments.
c) make life simpler for programmers.
d) may fail unexpectedly due to stress
(3) The constructor cannot have
a) more than five arguments b) new statement in body of constructor
c) return type d) all of above
(B) Do as directed. [9]
(1) Explain with an example: constant pointer and pointer to constant. [2]
(2) State TRUE or FALSE with justifications: [2]
i) “static functions are not true members of the class.”
ii) “The statement objA=objB; will cause a compiler error if the objects are of different
classes.”
(3) How the private data members are accessed outside the class? [1]
(4) Assume a class Person. It contains two integer data members and two member functions. [2]
One of the data members is static. What should be size of each object and total memory
allocated for five objects of the class? Write the importance of static data member.
(5) What is the meaning of following statement? Where D1 is the object of class Data. [2]
Data D1= Data(20,30);

Q.2 Answer the following questions. (Attempt any two) [12]


(A) Define an appropriate class for following main( ). Also write how many times constructor [6]
and copy constructor is called.
int main( )
{
Code A(100);
Code B(A);
Code C=A;
Code D;
D=A;
cout<<A.Display( )<<endl;
cout<<B.Display( )<<endl;
cout<<C.Display( )<<endl;
cout<<D.Display( )<<endl;
}
(B) Define a class called Book_Shop. It contains the title, total number of copies and prize as [6]
data members. It also contains two member functions for reading and printing all details.
Also write the member function to calculate total copies purchased and total money
collected. Take the array of five objects.
Q-2 (C) Define an examiner class only. Provide the necessary data members and member function [6]
for following:
The examiner must access answer sheets of at least one subject and may examine answer
sheets of multiple subjects, examiner represents a college and also a university and most of
the examiner are local and represent the local university. The program should have more
than one constructor including one with and one without default argument.

Q.3 (A) Assume the class Telephone_Directory is already defined. This has data members like [6]
name of subscriber, telephone number and address. Also two member function
InputDetails( ) andDisplayDetails( ) are already defined to take the input and print the
details. Write separate overloaded member functions to modify an entry according to (i)
name and (ii) telephone number. main( ) is not required.
(B) Define a class Height, which describes height of a person in meter and centimeter. Write a [6]
non-member function difference ( ) to calculate the difference between heights of two
objects/persons.main( ) is not required. [make difference( ) friend to the class Height]
OR
Q.3 (A) Write a function power( ) to raise a number m to a power n. The function takes a double [6]
value for m and int value for n, and returns the result correctly. Use a default value of 2 for
n to make the function to calculate squares when this argument is omitted. Write a main( )
that gets the values of m and n form the user to test the function. Also state why a single
default argument functions prevents the overloading of a same function without any
argument?
(B) What is function overloading? Why it is required? Is it possible to overload the function [3]
with default argument?
(C) Write an appropriate class definition for following main( ). [3]
void main( ) {
Person p1("abc"),p2("xyz",10), p3=p2;
p3.display( ); }

Page 2 of 2
DHARMSINH DESAI UNIVERSITY, NADIAD
FACULTY OF TECHNOLOGY
B.TECH. SEMESTER IV [ELECTRONICS & COMMUNICATION]
SUBJECT: (EC404) OBJECT ORIENTED PROGRAMMING
Examination : Second Sessional Seat No. : ___________
Date : 19/02/2015 Day :Friday
Time :11:00 to 12:15PM Max. Marks : 36
INSTRUCTIONS:
1. Figures to the right indicate maximum marks for that question.
2. The symbols used carry their usual meanings.
3. Assume suitable data, if required & mention them clearly.
4. Draw neat sketches wherever necessary.

Q.1 (A) Choose the most appropriate answer. [3]


(1) When a programmer does not want a class to be instantiated, it can be achieved by [1]
a) Defining a member function inside that class
b) Defining a friend function inside that class
c) Defining a virtual function inside that class
d) Defining a pure virtual function inside that class
(2) Which of the following operator can be overloaded through friend functions? [1]
a) . (dot operator) c) .* ( dereference member to)
b) ? : (conditional ternary) d) * (multiplication).
(3) Conversion from Object to built-in can be performed by [1]
a) Constructor b) conversion operators c) In-Built type cast d) none of these.

(B) Do as directed. [9]


(1) Assume that class is inheriting using private access specifier. Can we use public data [2]
member of base class from outside the class (main)? If yes, write syntax of it
(2) What is the size of derived class object for following class hierarchy? Assume that each [2]
class contains the two integer data members.
Class B {};
Class D1 : public B{};
Class D2: public B{};
Class X : virtual public D1, virtual public D2 {};
(3) Class Q is derives from Class P. The class Q does not contain any data member. Does the [1]
class Q require constructors? If yes, why?
(4) State TRUE or FALSE with justification,” User can overload *= operator for built in data [2]
types.”
(5) What is difference between overloading unary operator through member function and friend [1]
function?
(6) Why return type is not written during definition of typecast operator function? [1]

Q.2 Answer the following questions. (Attempt any two) [12]


(1) Define a class for following main. [6]
int main( )
{
Point p1,p2;
p1(2,3,4);
cout<<P1;
}
(2) Write a program to overload new and delete operator using malloc( ) and delete( ) function. [6]
(3) Define a class Cartesian and a class Polar, which have two data members x, y and angle, [6]
radius respectively. Write a program to overload = (assignment) operator to do P1=C1,
where P1 and P2 are objects of class Point.

Page 1 of 2
Q.3 (1) Define a class Faculty. Inherit a class Regular and Visiting faculty from Faculty class. [8]
Regular faculty is available full time and teaches at least three subjects. Where visiting
faculty is available only on two or three days and teaches a single subject. Provide the
constructors in each class to initialize data member. Also provide the member functions for
printing data members and calculate the salary of faculty. No need to write main function.

(2) What is importance of virtual keyword with member function? Explain with example. [4]
OR
Q.3 (1) Define a class called Vehicle. Inherits this class into two wheelers and four wheelers. [6]
Provide a function that calculates the mileage of the vehicle.(Distance travelled in km/fuel
consumed). Can we convert base class as abstract class? If yes, convert class as abstract
class.

(2) Find out the errors present in following code. Correct it and write the output. [6]

#include <iostream>
void showm( ) { cout << m << "\n"; }
using namespace std;
};
class base {
int main( )
private:
{
int i, j;
derived1 ob1;
public:
derived2 ob2;
void set(int a, int b) { i=a; j=b; }
ob1.set(2, 3);
void show( ) { cout << i << " " << j <<
ob1.show( );
"\n"; }
ob1.setk( );
};
ob1.showk( );
class derived1 : public base {
ob2.set(3, 4);
int k;
ob2.show( );
public:
ob2.setk( );
void setk ( ) { k = i*j; }
ob2.setm( );
void showk( ) { cout << k << "\n"; }
ob2.showk( );
};
ob2.showm( );
class derived2 : private derived1 {
return 0;
int m;
}
public:
void setm( ) { m = i-j; }

Page 2 of 2
DHARMSINH DESAI UNIVERSITY, NADIAD
FACULTY OF TECHNOLOGY
B.TECH. SEMESTER IV [ELECTRONICS & COMMUNICATION]
SUBJECT: (EC404) OBJECT ORIENTED PROGRAMMING
Examination : Third Sessional Seat No. : ___________
Date : 12/04/2016 Day : Tuesday
Time : 11:00 to 12:15 Max. Marks : 36
INSTRUCTIONS:
1. Figures to the right indicate maximum marks for that question.
2. The symbols used carry their usual meanings.
3. Assume suitable data, if required & mention them clearly.
4. Draw neat sketches wherever necessary.

Q.1 (A)Choose the most appropriate answer. [4]


(1) If we create a file by ‘fstream’, then the default mode of the file is _________
a) ios :: in b) ios :: out
c) ios :: app d) none
(2) The objects that can be stored and retrieved later are known as ___________.
a) serial objects. b) serialized objects
c) persistent object d) persisted objects
(3) Function templates can accept
a) any type of parameters b) only one parameter
c) only parameters of the basic type d) only parameters of the derived type
(4) Terminate( ) is called
a) No matching catch block is found
b) Throw an exception not present in list
c) Throw an exception without try block
d) All of above
(B) Do as directed. [8]
(1) State true/false with reason(s): “ The eof( ) function is false when the end-of-file has [2]
been reached”
(2) State true/false with reason(s): “When a file is opened in ios::app mode, the original [2]
content of the file will be lost”.
(3) Write a meaning of following expressions: [2]
a) class data <T *> b) thow;
(4) Is there any difference between template function and function overloading? If yes, write the [2]
situations in which it is required.

Q.2 Answer the following questions. (Attempt any two) [12]


(1) Define a template function Replace( ) which will replace the particular element of an array [3]
with new element. Check your program for integer and character data type.
[3]
(2) Write an exception handling program which will handle an exception occurs due to invalid [6]
marks enter by user. Program has to terminate, if user enter the five times invalid marks.
(3) a) Write syntax of template class which has three data members and two member functions [6]
(like getdata( ) and printdata( )). Out of three, two data members are two different
generic types and one data member is non generic type. Also write the syntax of
member function of the class.
b) Write general syntax for (i) User define Unexpected ( )
(ii) Restricting exceptions.

Q.3 (1) Write a program that splits a file into two separate text file. Invoke the program with two [6]
command-line arguments —the source file ,the destination file1 and the destination file2
like this:
$./a.out srcfile.cpp destfile1.cpp destfile2.cpp
In the program, check that the user has typed the correct number of command-line
arguments, and that the files specified can be opened.
(2) Explain use of following functions in using the text file with an example. [3]
seekg( ),tellg( ),open( )
(3) What are differences between binary file and text file? [3]

OR
Q.3 (1) What are file modes? Describe various file mode operations available [6]
(2) Write an object oriented program that reads a binary file containing 10 objects of class [6]
employee, Which has data members like name, employee_no and salary. Read the same
file and store the details in other file- "emp_list" based on ascending order of salary.

Page 1 of 1

You might also like