Oop Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 70
At a glance
Powered by AI
The laboratory manual outlines 10 labs covering topics related to object oriented programming such as classes, objects, inheritance, polymorphism and string manipulation.

The laboratory manual provides guidance to students on experiments and exercises to be performed in the lab related to the course titled Object Oriented Programming.

The manual covers topics such as functions, structures, classes, objects, operator overloading, inheritance, composition, polymorphism and string manipulation through 10 different labs.

GOVERNMENT VIQAR-UN-NISA POST GRADUATE COLLEGE FOR

WOMEN, RAWALPINDI
DEPARTMENT OF INFORMATION TECHNOLOGY

IT-202 Object Oriented Programming


LABORATORY MANUAL

Submitted by:
Iqra Zaman (030450)
Submitted to:
Ms. Shehzadi Ambreen
Course Code: IT-202
Credit Hour: 01

Student Name:hajra amin


Roll Number: 030472
Class: BS-IT(3rd Semester)

Sr. Lab Instructor’s


Lab Title Date
No. Number Signatures
1. LAB-01 Revision of Functions

2. LAB-02 Review of structure

3. LAB-03 Introduction to Classes and Objects


Classes and objects (II ),DMA (Dynamic
4. LAB-04
Memory Allocation)
5. LAB-05 Operator Overloading

6. LAB-06 Operator Overloading II

7. LAB-07 Inheritance

8. LAB-08 Composition

9. LAB-09 Polymorphism

10. LAB-10 String manipulation

Instructor’s Signatures: _______________________

2
Table of Contents

Lab 01:Revision of Functions..............................................................................................................................3

Lab 02:Review Of structure…………………………………………………………………………………….8

Lab03 :Introduction to Classes and Object...................................................................................................12

Lab 04:Classes and object (II ),DMA


(Dynamic Allocating Memory)..........................................................................................................................23

Lab 05:Operator Overloading...........................................................................................................................30

Lab 06:Operator Overloading (II)....................................................................................................................42

Lab 07:Inheritance................................................................................................................................................51

Lab 08:Composition.............................................................................................................................................58

Lab 09:Polymorphism.........................................................................................................................................66

Lab 10:String Manipulation...............................................................................................................................67

3
LAB 01

REVISION OF FUNCTIONS

Summary
Items Description
Course Title Object Oriented Programming
Lab Title Revision of Functions
Duration 3 Hours
Operating System /Tool/Language Dev C++ / Visual Studio
Objective Review of C++ functions

Objectives

You have already seen C++ functions in your first course on Programming. This lab
activity is intended to provide an overview/recap of:
 C++ Functions and theirusage
 Function definition, function declaration and function call
 The difference between call by value and call byreference
 Overloaded functions and functions with defaultparameters
 Recursive and inlinefunctions

4
LABTASKS

Task 1 :
Give answers to the following.
1. Write the prototype of a function named fnct() which accepts an int by value, a float by
reference and returns a char
output:
Char fnct(int a,float &b)
2. Using three variables a,b & c, call the function: double power(double, double);
Output:
c=power(a,b);

3. Which of these are valid function declarations:


a. voidfunction();
b. voidfunction(void);
c. voidfunction(int);
d. function(int);
e. intfunction();
Output:
a, b, c, e
4. A function needs to compute the average as well as the sum of three integers passed to it
and return the answers in the main(). Suggest the prototype for this function
Output:
float avg(arr[ ]);
5. What are inline functions?

Output:
The Function declared with keyword incline is known as incline function. The incline
function is declare before main function.

5
Task 02:

Write the output of the following code fragments.


1. int cube(int);
int main()
{
for(int i=0;i<10;i+=3)
cout << cube(i) << endl;
return 0;
}
int cube(int a)
{
return a*a*a;
}
Output:
0
27
216
729

2. int larger(int,int); int


main()
{
int x=10,y=5;
int m =larger(x,y);
cout<<m<<endl;
return0;
}
int larger(int a,int b)
{
if (a>b)
return a;
else return
b;
}
Output:
10

3. void decrement(int);
int main()
{
int x=10;
cout<< x
<<endl;
6
decrement(x);
cout<< x
<<endl;
return 0;
}
void decrement(int x)
{
x--;
cout<< x
<<endl; x--;
}

Output:
10
9
10

Task 03:
Write a program with a function isprime() which takes an integer as an argument and return
true if the argument is a prime number.
Program:
#include<iostream>
using namespace std;
bool isprime(int n);
int main()
{
int n,m;
cout<<"enter a number"<<endl;
cin>>n;
m=isprime(n);
cout<<" prime number "<<m<<endl;
return 0;
}
bool isprime (int n)
{
int i,c=1;
for(i=2;i<n ;i++)
{
if(n%i==0)
c=0;
}
if(c==1)
return true;
else
return false;
}

7
Execution Screen:

Task04:
Write a program with a function volume() which accepts three sides of a cube and return its
volume .Provide a default value of 1 for all the three sides of a cube .Call this function with zero,
one, two, and three arguments and display the volume returned in the main().

Program:
#include<iostream>
using namespace std;
int volume (int a=1, int b=1, int c=1)
{
return a*b*c;
}
int main()
{
int r;
r=volume();
r=volume(1,2,3);
cout<<"The Volume is "<<r<<endl;
}
Execution screen:

LAB 02

REVIEW OF STRUCTURES
8
Summary

Items Description
Course Title Object Oriented Programming
Lab Title Review of structures
Duration 3 Hours
Operating System /Tool/Language Visual Studio / Visual C++

Objective To get familiar with usage of Structures

Objectives
Before we move to Object Oriented Programming in its true sense, we will today revisit
C++ Structures which are closely related to classes. This lab session is intended to give a
recap of:
 Usage of astructure.
 Syntax of defining a structure and accessing itmembers.
 Using pointers tostructures.
 Nestedstructures.

9
LAB TASKS
Task 01 :
Write C++ code fragments for the following.
1. Declare a structure Time with fields hour, minute and second.
Output:
Struct Time
[
Int hours;
Int minutes;
Int second;
};
2. Declare a variable of type Time.
Output:
Int main()
{
Time t;
}
3. Declare a variable of type Time, a pointer to Time and an array of 10 Times. Assign the
address of the variable to the pointer.
Output:
Int main()
{
Time t;
Time *a;
Time arr[10];
Time =&a;
}
4. Using pointer variable set the value of hour to 5, minute to 10 and second to 50.
Output:
a->hours=5;
a->minutes=10;
a->second=50;
5. Declare a structure Date. Declare another structure Project with fields: ID, startDate and
endDate. (Use nested structures).
Output:
Struct Date
{
};
Struct Project
{
Int ID;
Date startDtae;
Date endDate;
};

6. How would you call the function void printTime(Time *) ?

10
Output:
PrintTime(Time *);

Task # 02:
Write a complete C++ program with the following features.
a. Declare a structure point with two integer members x and y
b. Define a function getInput(), which accepts a point by reference. Get user input for a
Point in this function.
c. Define a function addPoints(), which accepts two point p1 and p2.The function adds their
respective members, and returns a Point which is the sum of two. For example if one
point is (2,3), the other is (4,5), the function should return a point (6,8).
d. In the main(), declare two variables of point .Call the function getInput() twice to get the
values of these Point from user. Add the two Points using the Function addPoints() and
display the x and y values of the result returned by the function.

Program:

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
struct point
{
int x;
int y;
int result;
};
int getinput()
{
point p1,p2;
cout<<"Enter x:";
cin>>p1.x;
cout <<"Enter y:";
cin>>p1.y;
cout<<"Enter x:";
cin>>p2.x;
cout<<"Enter y:";
cin>>p2.y;
return 0;
}
int addpoints()
{
11
point p1,p2,result;
result.x=p1.x + p2.x;
result.y=p1.y + p2.y;
cout<<"the result of x value is:"<<result.x<<endl;
cout<<"the result of y value is:"<<result.y<<endl;
return 0;
}
int main()
{
getinput();
addpoints();
return 0;
}
Execution screen:

Task 03 :

a. Declare a Rectangle with two Points as its members, The top left and the bottom right.
b. Declare a variable of type Rectangle and get user input for the two points.
c. Define a function computeArea() which accepts a Rectangle and returns its area.
d. Display the area of the Rectangle in the main().

Program:

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
struct rectangle
{
int topleft;
int bottomright;
};
int computearea(rectangle b1)
{
int area=b1.topleft*b1.bottomright;
12
return area;
}
int main()
{
rectangle p1;
cout<<"Enter value of topleft:";
cin >>p1.topleft;
cout<<"Enter value of bottomright:";
cin>>p1.bottomright;
int z=computearea(p1);
cout<<"area is "<<z;
return 0;
}

Execution screen:

13
LAB 03

INTRODUCTION TOCLASSES ANDOBJECTS

Summary
Items Description
Course Title Object Oriented Programming
Lab Title Introduction to Classes and Objects

Duration 3 Hours
Operating System /Tool/Language Visual Studio / Visual C++

Objective To get familiar with concept of classes in c++

Objectives
The C++ programming skills that should be acquired in this lab:

 To understand what is an Abstract DataType


 To understand and use class, object, object instance andmessage.
 To understand the basic principles of data hiding andencapsulation.
 To understand and use keyword public andprivate.
 To understand and use constructor anddestructor.
 To understand the use of scope resolutionoperator.

14
LABTASKS
Task 01:
Write C++ code fragments for the following.

1. Declare a class Date with data members day, month, year

Output:
Class Date
{
Int days ;
Int month;
Int year;
}

2. Declare two objects of class Date.

Output:

Date D1 , D2;
3. Declare an object of class Date, a pointer to Date and an array of 10 Dates. Assign the
address of the object you declared to the pointer.

Output:
Date *ptr {10};
Ptr=new Date;
4. What is constructor?

Output:
A type of member function that is automatically executed when an object of that class is created is
known as constructor.

5. Suggest appropriate constructors for the Date class.

Output:

Date( )
6. How do you call the destructor ?

Output:

~Date( )

Task 02:
15
Write a program complete C++ program with the following features.

a. Declare a class point with two integers data members x and y


b. Provide appropriate constructors to initialize the data members
c. Provide separate get(getX( ) , getY( ) ) and set ( setX( ) , setY( ) ) method for each of
the data members
d. Provide method display ( ) to print the x and y coordinates .
e. In the main ( ) , declare two object of point and call the method display( ) for each of
them .Changes the value of x and y using set ( ) functions.
f. From main( ) , call the function getX ( ) and getY( ) for each of the points ,add the x
and y coordinates together and print the result.

Program:
#include<iostream>
#include<conio.h>
using namespace std;
class Point
{
private:
int x, y;
public:
Point()
{
x=100;
y=300;
}
int getX()
{
return x;
}

int getY()
{
return y;
}
void setX(int n)
{
x = n;
}

void setY(int m)
{ y = m;

16
}
void add(Point p1,Point p2 )
{

int a,b;

a=p1.getX()+p2.getX();

b=p1.getY()+p2.getY();

cout<<"The co-ordinates of point after adding are="<<a <<" "<<b<<endl;


}
void display( )
{
cout<<"The co-ordinates of point are="<<x<<" "<<y<<endl;

}
};
int main()
{
Point p1,p2;

p1.setX(2);

p1.setY(7);

p2.setX(9);

p2.setY(12);

p1.display( );

p2.display( );

p1.add(p1,p2 );
getch();
return 0;

}
Execution screen:

17
Task 03 :
Define a cycle Circle with its radius and center(x ,y) as data members . Provide appropriate
constructors and method to compute the area and circumferences of the circle.Call this method
from main ( ) program .
Program:
#include<iostream>
#include<conio.h>
using namespace std;
class Circle
{
private:
float radius;
int center;
public:
circle()
{
radius=0;
center=0;
}
void area(float radius)
{
cout<<"Area of circle :"<<3.14*radius*radius<<endl;
}
void circum(float radius)
{
cout<<"Circumference of circle :"<<2*3.14*radius<<endl;
}};
int main()
{
Circle C1;
float rad;
cout<<"Enter radius"<<endl;
cin>>rad;
C1.area(rad);
C1.circum(rad);
getch();
}
Execution screen:

18
LAB 04

CLASSES AND OBJECTS ( II ), DMA

(Dynamic Memory Allocation)

Summary
Items Description
Course Title Object Oriented Programming
Lab Title Classes and Objects (II),DMA
(Dynamic Memory Allocation )
Duration 3 Hours
Operating System /Tool/Language Visual Studio / Visual C++

Objective  To understand and implement pointers to


classes
 To dynamically allocate memory for
objects
 Separating class definition from
implementation

Objectives
This is the second session in the series of labs on objects and classes. This lab will enable
students:
 To understand and implement pointers toclasses
 To dynamically allocate memory forobjects
 Separating class definition fromimplementation

LABTASKS
19
Task 01:
Write C++ code fragments for the following.

1. Declare a class Distances with fields feet and inches (integers )

Output:
Class distance
{
Int feet ;
Int inches ;
}

2. Declare an object of type distance and a pointer to distance .Assign the address of the
object of pointer .
Output:

Distance d, *ptr;
Ptr = &d;

3. Write c++ statements to call the function display( ) of class Distance using : object , pointer
to object
Output:

Ptr -> display( );

4.
Declare a pointer to distances and allocate memory for an object using the keyword new

Output:

Distance *ptr ;
Ptr = new distance;

5. Suppose the distance class has constructor distance(int f,int i).Allocate memory for an
object of class distance using the keyword new in such a way that this constructor is
invoked
Output:
Distance d=new Distance

Task 02:
20
Write a complete C++ program with the following freatures :
a) Declare a class Time with three fields hour , minute and second
b) Provide appropriate constructors to initialize the data members.
c) Provide separate get( ) and set( ) method for each of the data members.
d) Provide a method display ( ) to print the Time.
e) In the main( ) , using dynamic allocating memory allocations , allocate memory for two
objects , currentTime and fligthTime ,
f) From main( ) , call the function gethour ( ) for the both Time objects and provide the
estimated number of hours in the departure of your flight ( no need to take the
account into minutes or seconds .

Program:
#include<iostream>
#include<conio.h>
using namespace std;
class Time
{
private:
int hour,min,sec;
public:
Time()
{
hour=min=sec=0;
}
void sethour(int x)
{
hour=x;
}
void setmin(int y)
{
min=y;
}
21
void setsec(int z)
{
sec=z;
}
int gethour()
{
cout<<"Enter time (hour):"<<endl;
cin>>hour;
return hour;
}
int getmin()
{
cout<<"Enter time (minutes):"<<endl;
cin>>min;
return min;
}
int getsec()
{
cout<<"Enter time (seconds)"<<endl;
cin>>sec;
return sec;
}
void display()
{
cout<<"the time is:"<<hour<<":"<<min<<":"<<sec<<endl;
}
};
int main()
{
Time *ct, *ft;
ct=new Time;
22
ft=new Time;
ct->gethour();
ct->getmin();
ct->getsec();
ft->gethour();
ft->getmin();
ft->getsec();
ct->display();
ft->display();
ct->sethour(2);
ct->setmin(21);
ct->setsec(45);
ft->sethour(1);
ft->setmin(29);
ft->setsec(30);
ct->display();
ft->display();
cout<<"Estimated number of hours in the departure of flight="<<ct->gethour()-ft->gethour()<<endl;
getch();
return 0;
}

Execution screen:

23
Task 03:

Implement the program in exercise 1 by putting the class definition in a header


file, the class implementation in a cpp file and the main program in a separate cpp
file.

Program:

 Header File:
#include<iostream>
#include<conio.h>
using namespace std;
class Time
{
private:
int hour,min,sec;
public:
Time()
{
hour=min=sec=0;
}

void sethour(int x)
{
24
hour=x;
}
void setmin(int y)
{
min=y;
}
void setsec(int z)
{
sec=z;
}
int gethour()
{
cout<<"Enter time (hour):"<<endl;

cin>>hour;
return hour;
}

void getmin()

cout<<"Enter time (minutes):"<<endl;

cin>>min;

void getsec()
{

cout<<"Enter time (seconds)"<<endl;

cin>>sec;
}
void display()
{
cout<<"the time is:"<<hour<<":"<<min<<":"<<sec<<endl;

}
};

 Main File :

#include <iostream>
using namespace std;
#include"TIME.h"
25
int main()

Time *ct, *ft;

ct=new Time;

ft=new Time;
ct->gethour();
ct->getmin();
ct->getsec();
ft->gethour();
ft->getmin();
ft->getsec();
ct->display();
ft->display();
ct->sethour(2);
ct->setmin(21);
ct->setsec(45);
ft->sethour(1);
ft->setmin(29);
ft->setsec(30);
ct->display();
ft->display();
cout<<"Estimated number of hours in the departure of flight="<<ct->gethour()-ft-
>gethour()<<endl;
getch();

return 0;

26
Execution screen:

27
LAB 05

OPEARTOR OVERLOADING
Summary

Items Description
Course Title Object Oriented Programming
Lab Title Operator Overloading
Duration 3 Hours
Operating System /Tool/Language Visual Studio/ Visual C++

Objective To understand the concept of operator


overloading and its syntax and, overload
arithmetic unary and binary operators

Objectives:

To understand the concept of operator overloading and its syntax and, overload arithmetic unary and
binary operators

28
LABTASKS

Task 01:
Write C++ code fragments for the following.
1. What is operator overloading ?

Ans :The term “operator overloading “ refers to giving the normal C++ operators, such as +, *,
<= and ++ additional meanings whn they are applied to user-defined data types.It is one of the
most exciting features of object oriented programming .It can transform complex, obscure
program listing into intuitively obvious ones.

2. Is it possible to overload the ‘+’ operator for data type int ?

Ans:No ,it is not possible to overload ‘+’ operator for any built-in data type like int or float.
Operator overloading is designed to allow you to extend the language, not to change it,At least one of
the parameters of an overloaded operator must be a user defined type (class or num type) or a
reference to a user defined type.

3. How do we differentiate between prefix and postfix increment operator while overloading
them?

Ans:To differentiate between prefix and postfix increment operator C++ uses a “dummy variable” or
“dummy argument” for any one of the two operators.This argument is a fake integer parameter that
only serves to distinguish the postfix version of increment from the prefix version. Another difference is
that postfix increment changed the incremented object, but returns a version of it before the
increment.The prefix increment changes the object and returns the incremented version.

4. What is the syntax of overloading ‘*’ operator for a class matrix (you do not need to write the
body of the function)

Ans:Syntax:

Matrix operator * (matrix)

{ }
5. Write the output of the given code segment.
Counter c1(5),c2(10),c3;
c3=c1++;
c2=--c3;
cout<<’\n’<<<’c1.get_count();
cout<<’\n’<<<c2.get_count();
cout<<’\n’<<<c3.get_count();
Output:
6
4
4

29
Task 02 :
Write a complete C++ program with the following features
• Declare a class Time with two fields hour and minute.
• Provide appropriate constructors to initialize the data members.
• Overload the pre and postfix increment operators to increment the minutes by one.Also
make sure if minutes are 59 and you increment the Time it should update hours and
minutes accordingly.
• Provide a function display() to display the hours and minutes.
• In main(), create two objects of Time, initialize them using constructors and call the
display functions.
• Test the following in your main:
a. T3=++T1;
b. T4=T2++;

Program:
#include<iostream>
#include<conio.h>
using namespace std;
class Time
{
private:
int hour;
int minute;
public:
Time()
{
hour=0;
minute=0;
}
Time(int h,int m)
{
hour=h;
minute=m;
}
Time(int m):minute(m)
{
}
void showdata()
{
cout<<"Hours="<<hour<<endl;
cout<<"Minutes="<<minute<<endl;
30
}
void operator++()
{
++minute;
if(minute>59)
{
++hour;
minute=minute-60;
}
cout<<hour<<"\t"<<minute<<endl;
}
void operator++(int)
{
minute++;
if(minute>59)
{
hour++;
minute=minute-60;
}
cout<<hour<<"\t"<<minute<<endl;
}

};
int main()
{
Time T1(7,50);
Time T2(8,66);
T1.showdata();
T2.showdata();
++T1;
T2++;
getch();

Execution Screen:

31
Task 03 :
Write a class complex to model complex numbers and overload the ‘+’and ‘-‘
Operators. Separate the class declaration and class implementation in header and cpp files.

Program:

 Header file:

#ifndefCOMPLEX
#defineCOMPLEX
#include<iostream>
using namespace std;
class Complex
{
private:
float real;
float imagnary ;
public:
void set();
void showdata();
Complex operator+ (Complex ob5);
Complex operator-(Complex ob6);
};
#endif

 Source file:

#include<iostream>
#include "COMPLEX.h"
void Complex::set()
{
cout<<"Enter real Number:"<<endl;
cin>>real;
cout<<"Enter imaginary Number:"<<endl;
cin>>imagnary;
}
void Complex::showdata()
{
cout<<"Real="<<real<<endl;
cout<<"Imaginary="<<imaginary<<endl;
32
}
Complex Complex::operator+(Complex ob5)
{
complex temp;
temp.real=real+ob5.real
temp.imaginary=imaginary+ob5.imaginary;
return temp;
}
Complex Complex::operator-(Complex ob6)
{

Complex temp;
temp.real=real-ob6.real;
temp.imaginary=imaginary-ob6.imaginary;
return temp;
}

 Main file:

#include<iostream>
using namespace std;
#include "COMPLEX.h"

int main(int argc, char** argv)


{
Complex ob1;
Complex ob2;
Complex ob3, ob4;
ob1.set();
ob2.set();
ob1.showdata();
ob2.showdata();
ob3=ob1+ob2;
ob4=ob1-ob2;
ob3.showdata();
ob4.showdata();
return 0;
}

33
Execution screen:

34
LAB 06

OPEARTOR OVERLOADING II
Summary

Items Description
Course Title Object Oriented Programming
Lab Title Operator Overloading II
Duration 3 Hours
Operating System /Tool/Language Visual Studio/ Visual C++

Objective To get familiar with overloading Relational


Operator and also learn how to overload
operations using non-member functions.

Objectives
This lab is second in the series of labs on operator overloading. Students should be
abletooverloadrelationaloperatorsbytheendofthislab.Studentswillalsolearnhowtooverload
operators using non-memberfunctions
LABTASKS

Task 01:
Answer the following/Write C++ code where required.

1. Write the declaration of function to overload = = operator for a D class members feet
and inches.

Ans:

bool operator ++(Distance d1);

2. Write the declaration of a function in part 1 as above inherited as a no member


function.

Ans: bool operator = = (Distance d2,Distance d3);

3. Can we overload the ‘<’ operator for integer?

Ans: No, we cannot overload any operator for built-in data types such as int, float,
char defined data types. So, we cannot overload the ‘<’ operator for integers.

4. Using operator overloading can we change the number of operands of an operator?

Ans: The number of operands an operator takes cannot be changed unary remains
unary, binary remain binary. Changing the number of an operands of an operator
overloading is against the rules of operator overloading.

5. Assume that ‘+’ is overload for class Distance. Can we write the following statements:

Distance d1,d2(3,4), d3(4,5),D4(6,7);

d1=d2+d3+d4;

Ans: yes, we can write the above statements. In the first statement, we defined 4
objects of class Distance. For the first object default constructor is called
automatically, but the other three objects are initialized by some vale given using
overloaded constructor. And in the second statement, add the values of d2,d3 and d4
to obtain d1.

Task 02:

36
Create a class integer to stimulate the integer data type in C++. The class will have one
integer data member. Provide constructors to get/set() methods. Overload the following
relational operators:

<, >, ==, !=, +, -

Overload each of the following relational operator, using class member functions.

Program:
#include<iostream>

using namespace std;

class integer

private:

int a;

public:

integer():a(0)

{}

ineger(int s)

a=s;

void set_data()

cout<<"enter a number: ";

cin>>a;

void display()

37
cout<<a<<endl;

integer operator+( integer b)

integer temp;

temp.a=a+b.a;

return temp;

integer operator-( integer c)

integer temp;

temp.a=a-c.a;

return temp;

bool operator==( integer d)

if(a==d.a)

return 1;

else

return 0;

bool operator>( integer e)

if(a>e.a)

return 1;

38
else

return 0;

bool operator<( integer f)

if(a<f.a)

return 1;

else

return 0;

bool operator!=( integer g)

if(a!=g.a)

return 1;

else

return 0;

};

int main()

integer O1,O2,O3,O4;

O1.set_data();

O2.set_data();

O1.display();

39
O2.display();

O3=O1+O2;

cout<<"the sum of integers: ";

O3.display();

O4=O1-O2;

cout<<"The diffrence of integers: ";

O4.display();

if(O1==O2)

cout<<"The two integers are equal."<<endl;

else

cout<<"The integers are not equal."<<endl;

if(O1>O2)

cout<<"The 1st integer is greater than 2nd integer."<<endl;

else

cout<<"The 2nd integer is greater than 1st integer."<<endl;

if(O1<O2)

cout<<"The 1st integer is less than 2nd integer."<<endl;

else

cout<<"The 2nd integer is less than 1st integer."<<endl;

if(O1!=O2)

cout<<"The two integers are different."<<endl;

else

cout<<"The integers are not different."<<endl;

return 0;

40
Execution screen:

41
LAB 07

COMPOSITION

Summary

Items Description
Couse Title Object Oriented Programming
Lab Title Composition
Duration 3 Hours
Operation System Tool / Visual Studio
Language
Objective  To understand the concept of Has-A relationship.
 To understand the design of a composite class.
 To learn the use of class member initialize syntax.
 To understand the use of ‘this’ pointer.

Objectives:

 To understand the concept of Has-A relationship.


 To understand the design of a composite class.
 To learn the use of class member initialize syntax.
 To understand the use of ‘this’ pointer.

LAB TASKS

42
Task 1:
Create a class point with two data members x and y. Provide appropriate constructors,
get , set and display methods.
Create a class Triangle with three points as its data members. Provide appropriate
constructors for this class and a display method which calls the display methods of the
three points.
In the main function, declare three points and pass them to the constructor of the class
Triangle. Call the display method of Triangle to verify the coordinates of the Triangle.

Program:
#include<iostream>
using namespace std;
class point
{
private:
int x, y;
public:
point():x(0),y(0)
{}
void set(int a,int b)
{
x=a;
y=b;
}
int get_x()
{
return x;
}
int get_y()
{
return y;
}
void display()
{
cout<<"The points are :("<<x<<","<<y<<")"<<endl;
}
};
class Triangle
{
private:
point i,j,k;
public:
Triangle(point p1,point p2, point p3)
{
i=p1;
j=p2;

43
k=p3;
}
void display()
{
i.display();
j.display();
k.display();
}
};
int main()
{
point m,n,o;
m.set(3,6);
m.get_x();
m.get_y();
n.set(6,4);
n.get_x();
n.get_y();
o.set(5,8);
o.get_x();
o.get_y();
Triangle t(m,n,o);
t.display();
return 0;
}
Execution screen:

Task 2:

Create separate header file(s) for the above code for each of the class definition and
separate .cpp file for your main().

Program:

44
 Header file (POINT):
#ifndef POINT
#define POINT
#include<iostream>
using namespace std;
class Point
{
private:
int x,y;
public:
void set(int a,int b);
int get_x();
int get_y();
void display();
};
#endif
 Source file (POINT):
#include<iostream>
using namespace std;
#include"POINT.h"
void Point ::set(int a,int b)
{
x=a;
y=b;
}
int Point::get_x()
{
return x;
}
int Point::get_y();
{
return y;
}
void Point::display();
{
cout<<"The points are:("<<x<<","<<y<<")"<<endl;
}

 Header file (TRIANGLE):

#ifndef TRIANGLE
#define TRIANGLE
#include<iostream>
using namespace std;
#include"POINT.h"
class Triangle

45
{
private:
Point i;
Point j;
Point k;
public:
Triangle(Point p1,Point p2, Point p3)
void display();
};
#endif

 Source file (Triangle):

#include<iostream>
using namespace std;
#include"POINT.h"
#include"TRIANGLE.h"
Triangle::Triangle(Point p1,Point p2, Point p3)
{
i=p1;
j=p2;
k=p3;
}
void Triangle:: display()
{
i.display();
j.display();
k.display();
}

 Main file:

#include<iostream>
using namespace std;
#include"POINT.h"
#include"TRIANGLE.h"

/* run this program using the console pauser or add your own getch, system("pause") or input
loop*/

int main(int argc,char** argv)


{
Point m,n,o;
m.set(5,9);
m.get_x();
m.get_y();

46
n.set(3,7);
n.get_x();
n.get_y();
o.set(2,8);
o.get_x();
o.get_y();
Triangle t(m,n,o);
t.display();
return 0;
}

Execution screen:

47
LAB 08
INHERITANCE
Summary

Items Description
Couse Title Object Oriented Programming
Lab Title Inheritance
Duration 3 Hours
Operation System Tool / Visual Studio
Language
Objective To understand the concept of inheritance.
.

Objectives:

The C++ programming skills that should be acquired in this lab:


 To understand the concept of inheritance.
 To understand the use of protected class members.
 Implement inheritance in C++.
 To understand the concept of multiple inheritance.

48
LAB TASKS:

Task 1:
Answer the following/Write C++ code where required.

1. Class A: public class B{}


State which members(public/protected/private) of class A can be access from class
B.
Public and protected members of class $ can be accessed from class B.
2. Class Square can be derived from class Rectangle. Write the constructor (one
argument) of class Square and call the (two argument) constructor of Rectangle
Output:
class Square: public Rectangle
{
private:
int c;
public:
Square (int x, int y, int z):Rectangle (x,y)
{
C=z;
}
};
int main()
Square s;
}
3. Are overloaded operators inherited in the derived class?
Ans: All overloaded operators except assignment operator (==) are inherited by
derived classes. The first argument for member-function overloaded is always of
the class type object for which the operator invoked ( the class in which the
operator is declared, or a class derived from that class).
4. Consider the following code:

class A
{
public:
A()
{
cout<<”A:default” <<endl;
}
A(int a)
{
cout<<”A:parameter”<<endl;
}
};
Class B: public A

49
{
public:
B (int a)
{
cout<<”B”<<<<endl;
}
};

Write the output of :


a) B b(2)
b) B b2;

Output:
a) A: default
B

b) This statement gives an error because there is no matching function for call to
‘B:B()’

5. The class B in the above question is changed as follows:


class B: public A
{
public:
B(int a) : public (a)
{
cout<<”B”<<endl;
}
};

Write the output of:


B test(5);

Output:
A:parameter
B

Task 2:

Create a class Point with two data members x and y. Provide appropriate constructors, get,
set and display methods.

Derive a class Circle from Point. The Circle in addition to the center (Point) also has radius
as its data member. Provide constructors, get and set methods in the circle class. Also
provide methods to compute area and circumference of the circle. (Area of circle PI * r* * r
and circumference is: 2 * PI * r).

50
Derive a class Cylinder from circle with a data member height. Provide constructors and
set/get methods to set/get height of the cylinder. Provide a function to compute area
cylinder. (A = 2 * area of circle + 2 *PP * r* height). Also provide a function to compute the
volume of cylinder (PI*r* r* h). Create an object of class Cylinder and compute its volume
and surface area.

Program:

#include<iostream>
using namespace std;
class Point
{
protected:
int x , y;
public:
Point():x(0),y(0)
{}
Point(int a, int b)
{
a=x;
b=y;
}
void set_data()
{
cout<<"Enter value of x anf y :"<<endl;
cin>>x>>y;
}
int get_x()
{
return x;
}
int set_y()
{
return y;
}
void display()
{
cout<<"x="<<x<<endl;
}
};
class Circle
{
protected:
int radius;
public:
Circle(): radius(0)

51
{}
Circle (int r)
{
r=radius;
}
void set_r()
{
cout<<"Enter radius: "<<endl;
cin>>radius;
}
int get_r()
{
return radius;
}
float area()
{
float a;
a=3.1415 * radius * radius;
return a;
}
void circum()
{
float c;
c=2 * 3.1415 * radius;
cout<<"The circumference is: "<<c<<endl;
}
};
class Cylinder: public Circle
{
private:
int height;
public:
Cylinder(): height(0)
{}
Cylinder (int h)
{
h=height;
}
void set_h()
{
cout<<"Enter the Height :"<<endl;
cin>>height;
}
int get_h()
{
return height;

52
}
void area()
{
float A;
A = 2 * (Circle::area()) + 2* 3.1415 *radius * height;
cout<<"The area of cylinder is:"<<A<<endl;
}
void volume()
{
float v;
v = 3.3434 * radius *radius *height;
cout<<"The volume of cylinder is:"<<v<<endl;
}
};
int main()
{
Cylinder obj;
obj.set_h();
obj.set_r();
obj.area();
obj.volume();
return 0;
}

Execution screen:

Task 3:

Write the above program by creating a sperate (header+source) file for each of the class.
Therefore, you will have 3 header and3 souce files for the three classes and one source file
for yur main program.

53
Program:
 Header files:

1. POINT(H):
#ifndef POINT
#define POINT
#include<iostream>
using namespace std;
class Point
{
protected:
int x,y;
public:
void set_data();
int get_x();
int get_y();
void display();
};
#endif

2. CIRCLE (H):

#ifndef CIRCLE
#define CIRCLE
#include<iostream>
using namespace std;
#include"POINT.h"
class Circle:public Point
{
protected:
int radius;
public:
int get_r();
void set_r();
float area();
void circum();
};
#endif

3. CYLINDER (H):

#ifndef CYLINDER
#define CYLINDER
#include<iostream>
using namespace std;

54
#include"CIRCLE.h"
class Cylinder:public Circle
{
private:
int height;
public:
int get_h();
void set_h();
void area();
void volume();
};
#endif

 Source files:

1. POINT(S):

#include<iostream>
using namespace std;
#include"POINT.h"
void Point ::set_data()
{
cout<<"ENTER VALUE OF X:"<<endl;
cin>>x;
cout<<"ENTER VALUE OF Y:"<<endl;
cin>>y;
}
int Point::get_x()
{
return x;
}
int Point::get_y();
{
return y;
}
void Point::display();
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
}

2. CIRCLE (S):

#include<iostream>
using namespace std;

55
#include"CIRCLE.h"
void Circle::set_r()
{
cout<<"Enter radius:"<<endl;
cin>radius;
}
int Circle::get_r()
{
return radius;
}
float Circle::area()
{
float a;
a=3.1415*radius*radius;
return a;
}
void Circle::circum()
{
float c;
c=2*3.1415*radius;
cout<<"The circumference is:"<<c<<endl;
}

3. CYLINDER (S):

#include<iostream>
using namespace std;
#include"CYLINDER.h"
void Cylinder::set_h()
{
cout<<"Enter height:"<<endl;
cin>>height;
}
int Cylinder::get_h()
{
return height;
}
void Cylinder::area()
{
float A;
A=2*(Circle::area())+2*3.1415*radius*height;
}
void Cylinder::volume()
{
float v;
c=3.1415*radius*radius*height;

56
cout<<"The volume of cylinder is:"<<v<<endl;
}

 Main file:

#include<iostream>
using namespace std;
#include"POINT.h"
#include"CIRCLE.h"
#include"CYLINDER.h"

/* run this program using the console pauser or add your own getch, system("pause") or
input loop*/

int main(int argc,char** argv)


{
Cylinder obj;
obj.set_data();
obj.set_h();
obj.set_r();
obj.area();
obj.volume();
return 0;
}

Execution screen:

57
LAB 09
POLYMORPHISM

Summary

Items Description
Couse Title Object Oriented Programming
Lab Title Polymorphism
Duration 3 Hours
Operation System Tool / Visual C++ /Visual studio
Language
Objective To understand the use of pointers to base class.
.

Objectives:

The C++ programming skills that should be acquired in this lab:

 To understand the use of pointers to base class.


 To understand the syntax of defining a virtual function.
 To understand the use of abstract classes.
 To understand the use of pure virtual functions.

58
LAB TASKS
Answer the following/Write C++ code where required.

1. Consider a class Square derived from a class Quad. Declare a pointer to Quad and
assign the address of an object of class Square to this pointer.
Output:
int main()
{
Square s;
Quad *p;
p=&s;
}
2. Repeat the above using dynamic memory allocation, i.e. allocate memory for an
object of class Square and assign the address to a pointer of class Quad.
Output:
int main()
{
Quad *p;
p=new Square;
}
3. Both Quad and Square have a method int area(); which of the method is called by
the following statement.
Quad quad, *ptrQuad;
Square sq;
ptrQuad=&sq;
quad.area();
ptrQuad -> area();
Ans: The method int area() defined in base class (Quad) is called two times by the
above statements.
4. Repeat exercise 3 assuming that area() is declared as virtual function.

59
Ans:Quad.area() is called is called from base class (Quad whereas ptrQuad-
>area() is called from derived class(Square).
5. What is an abstract class? What makes a class abstract?
Ans:Abstract class is that class which contains at least one pure virtual function
(which make an object as the pure virtual functions has no implementation but a
pointer can be made which can only point to the objects of derived class.

Task 02:

Create an abstract class Faculty with fields name and ID. Provide a pure virtual function
salary(). Derive a class Permanent Faculty from Faculty. The class has additional attributes
years of service and basic pay. The salary of permanent faculty is computed as the sum of
basic pay, medical allowance and house rent. Medical allowance is 10% of basic pay and
house rent is 25% of the basic pay.

Derive another class Visiting Faculty from Faculty. The class has attributes per hour rate
and number of hours taught. The salary of visiting faculty is computed by multiplying the
per hour rate with the number of hours taught. Write a program to declare two pointers of
class Faculty. Create an object each of visiting and permanent faculty, assign their
addresses to pointers of base class, set the values of data members and call the salary
function for each.

Program:

#include<iostream>
#include<string>
using namespace std;
class faculty
{
protected:
int ID;
string name;
public:
faculty():ID(0),name("\0")
{}
faculty (int i, string a)
{
ID=i;
name=a;
}
void set()
{
cout<<"Enter name :"<<endl;
cin>>name;

60
cout<<"Enter ID: "<<endl;
cin>>ID;
}
virtual float salary()=0;
};
class pf:public faculty
{
private:
int years, bp;
public:
pf():years(0),bp(0),faculty()
{}
pf(int i, string a,int x,int y):faculty(i,a),years(x),bp(y)
{}
void set_years()
{
cout<<"Enter the name of years :";
cin>>bp;
}
void set_bp()
{
cout<<"Enter basic pay : ";
cin>>bp;
}
float salary()
{
return (bp+(bp*0.1)+(bp*0.25));
}
};
class vf:public faculty
{
private:
int hr;
int number_of_hr;
public:
vf():hr(0),number_of_hr(0),faculty()
{}
vf(int i,string a,int x,int y):faculty(i,a),hr(x),number_of_hr(y)
{}
void set_hr()
{
cout<<"Enter hour rate : ";
cin>>hr;
}
void set_noh()
{

61
cout<<"Enter number of hour : ";
cin>>number_of_hr;
}
float salary()
{
return (hr*number_of_hr);
}
};
int main()
{
pf p;
vf v;
faculty *p1,*p2;
p1=&p;
cout<<"Enter permanent member details:\n";
p1->set();
p.set_bp();
p.set_years();
cout<<"Salary:"<<p1->salary()<<"\n\n";
p2=&v;
cout<<"Enter visiting member details:\n";
p2->set();
v.set_hr();
v.set_noh();
cout<<"Salary: "<<p2->salary()<<"\n\n";
return 0;
}

Execution Screen:

62
Task 03:
Modify the above program to declare an array of pointers o faculty. Using dynamic
memory allocation, create an object of permanent or visiting or visiting faculty as indicated
by the user (Get user choice).
Once the user has entered data for faculty, call the salary method for each object and
display the salary.

Program:

#include<iostream>
#include<string>
using namespace std;
class faculty
{
protected:
int ID;
string name;
public:
faculty():ID(0),name("\0")
{}
faculty (int i, string a)
{
ID=i;
name=a;
}
void set()
{
cout<<"Enter name :";
cin>>name;
cout<<"Enter ID: ";
cin>>ID;
}
virtual float salary()=0;
};
class pf:public faculty
{
private:
int years, bp;
public:
pf():years(0),bp(0),faculty()
{}
pf(int i, string a,int x,int y):faculty(i,a),years(x),bp(y)
{}
void set_years()
{

63
cout<<"Enter the years of service :";
cin>>years;
}
void set_bp()
{
cout<<"Enter basic pay : ";
cin>>bp;
}
float salary()
{
return (bp+(bp*0.1)+(bp*0.25));
}
};
class vf:public faculty
{
private:
int hr;
int number_of_hr;
public:
vf():hr(0),number_of_hr(0),faculty()
{}
vf(int i,string a,int x,int y):faculty(i,a),hr(x),number_of_hr(y)
{}
void set_hr()
{
cout<<"Enter hour rate : ";
cin>>hr;
}
void set_noh()
{
cout<<"Enter number of hour : ";
cin>>number_of_hr;
}
float salary()
{
return (hr*number_of_hr);
}
};
int main()
{
faculty *p[3];
char a;
cout<<"Enter p for permanent member and v for visiting member:";
cin>>a;
if(a=='p')
{

64
p[0]=new pf(1,"rida",5,5000);
cout<<"Salary:"<<p[0]->salary()<<endl;
}
else if(a=='v')
{
p[1]=new vf(2,"hira",14,400);
cout<<"Salary: "<<p[1]->salary()<<endl;
}
else
cout<<"Invalid"<<endl;
return 0;
}

Execution screen:

 For permanent member:

 For visiting member:

 Invalid case:

65
LAB 10
STRING MANIPULATION
Summary

Items Description
Couse Title Object Oriented Programming
Lab Title String Manipulation
Duration 3 Hours
Operation System Tool / Visual C++ /Visual studio
Language
Objective To understand the use of strings.
.

Objectives:

The C++ programming skills that should be acquired in this lab:

 To understand the use of string.


 To understand the use of string I\O.
 To understand the use ofString Manipulation.
 To understand the use of C-string I\O functions.

66
LAB TASKS
Write the output of the following code fragments:
1. string s1;
s1=”Anatoliy:”;
cout<<”s1 is:”<<s1<<endl;
//copy constructor
string s2 (s1);
cout<<”s2 is: “<<s2<<endl;

Output:
s1 is: Anatoliy
s2 is: Anatoliy
2. string str =”Hello”;
cout<<”str is: “<<str<<endl;
str +=”,”;
str+=’ ‘;
cout<<”str is : “<<str<<endl;
string s;
s= str + “World”;
cout<<”s is : “<<s<<endl;
char ch=’!’;
s +=ch;
cout<<”s is : “<<s<<endl;

Output:
str is: Hello
str is: Hello,
s is: Hello, World
s is: Hello, World!
3. string s= “No body is perfect”;
//Returns s[pos]
for( int pos = 0;pos < s.length();++pos)
cout <<s.at(pos<<” “;
cout<<endl;
Output:
No body is perfect
4. string s3(line);
cout<<”s3 is: “<<s3<<endl;
string s4 (line,10);
//1- C++ string
//2- start position
// 3- number of characters
string s5 (s3,6,4);
cout<<”s5 is: “<<s5<<endl;

67
Output:
s3 is: Hello world
s4 is: d
s5 is: Worl
5. string s6(15,’*’);
cout<<”s6 is: “<<s6<<endl;
string s7 (s3.begin(),s3.end()-5);
cout<<”s7 is: “<<s7<<endl;
Output:
s6 is: ***************
s7 is: Hello
6. string str = “No body is perfect “;
string s =” ”; //empty string
char *ch = “abcdef”;
s.append(str, 0, 6);
cout<<”s is : “<<s<<endl;
string::iterator inplt1 =str.begin() +6;
string::iterator inplt2 = str.end();
s.append(inplt1,inplt2);
cout<<”s is : “<<s<<endl;
s.append(3,’!’);
cout<<”s is : “<<s<<endl;
s.append(ch,3);
cout<<”s is : “<<s<<endl;
s.append(ch,3);
cout<<”s is : “<<s<<endl;
Output:
s is : No body
s is : No body is perfect
s is : No body is perfect!!!
s is : No body is perfect!!!abc
s is : No body is perfect!!!abcabc
7. string str = ”We go step by step to the target”;
cout<<”str is : “<<str<<endl;
int n = str.find(“step”);
string s = str.substr(n);
cout<<”s is: “<<s<<endl;
s = str.substr(n,12);
cout<<”s is: “<<s<<endl;
Output:
str is: We go to step by step to the target
s is: step by step to the target
s is: step by step

68
Task 02:

Write a program which prompts user to enter a string of text. Once entered , you need to
present a
Summary of the text in the following manner.
Total number of vowels in the text.
Total number of spaces in the text.
Total number of upper case characters in the text.
Program:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int vowel=0, space=0, upper=0;
string s;
cout<<"Enter string: ";
getline(cin,s);
for(int i=0; i<(s.length());i++)
{
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u')
vowel++;
else if(s[i]==' ')
space++;
else if(isupper(s[i]))
upper++;
}
cout<<"\nNumber of vowels: "<<vowel<<endl;
cout<<"\nNumber of spaces: "<<space<<endl;
cout<<"\nNumber of uppercase letters: "<<upper<<endl;
return 0;
}

Execution screen:

69
Task 03:

Write a program that reads an identification number which could be an ID card number in
the following format:
XXXXX-XXXXXXX-X or a social security number in the following format XXX-XX-
XXXX.
The different fields of the ID card /SS number are separated by a ‘-‘. Using members of the
string class separate the different fields of the identification number and display each field.

Program:

#include<iostream>
#include<string>
using namespace std;
int main()
{
string s,s1,s2,s3;
cout<<"Enter a string in format XXXXX-XXXXXXX-X: ";
getline(cin,s);
s1=s.substr(0,3);
s2=s.substr(3,2);
s3=s.substr(6,4);
cout<<"\nString in format XXX-XX-XXXX: "<<s1<<"-"<<s2<<"-"<<s3<<endl;
return 0;
}

Execution screen:

70

You might also like