Professional Documents
Culture Documents
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Define OOP
THEORY
2
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Data abstraction: is a
Encapsulation: is a process
process to delete all
of tying together all data and
unnecessary attributes and
methods that form a class and
remain the necessary
control the access to data by
attributes to describe an
hiding its information.
object.
4 Main
concepts of
OOP
Polymorphism: Polymorphism is
processes of giving the same Inheritance: Create a new
message to another two or more class from an existing class
different objects and produce together with new attributes
different behaviors depend on and behaviors.
how the objects receive the
message.
ACTIVITY 1
Procedure:
Look at the output from application below.The applicaion can accept the data given by the
user (name, regs. No, course and mark), then there are other functions to calculate the
gred depend on the mark. At last the information will display like below :
3
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Object : Student
Data : Name, Regs. Number, Course, Mark
Method : Accept()
Calculate()
Display()
EXERCISE
1. Table below show all the information about staff in SYARIKAT BUDI. [10M]
4
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Create an application to accept all the data as show in the information above. Other than
that, there are other functions to calculate the total years working and display all the
information like:
2. Using data abstraction, take out all the data and functions that are needed to create this application.
Object : ____________________
Data : ________________________________________________________
Method : ____________________
____________________
____________________
3. Use the data encapsulation concept to gather all the data and appropriate functions into the class.
______________________
{
__________________
__________________
__________________
__________________
__________________
__________________
__________________
Public:
_______________ ( );
_______________( );
_______________ ( );
};
NOTES
5
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Create classes based on the general form of a class.
2. Use member function (methods) in OOP languages.
3. Create objects for a class
4. Manipulate the encapsulation concepts
THEORY
6
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Object are created from classes by instantiating them; the syntax to declare the
object is
className ClassObjectName;
• A member function can be declared inside the class or defined outside the class. When
defined outside the class, the scope resolution operator must be used.
ACTIVITY 2A
Program to display the student's details
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab2A.cpp.
#include <iostream.h>
class Student
{
public:
char name[25];
long int phone;
void accept()
{
cout<<"\nEnter the student\'s name : ";
cin>>name;
cout<<"\nEnter the phone number : ";
cin>>phone;
}
7
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
void display()
{
cout<<"\n Student\'s name : "<<name;
cout<<"\n Phone number : "<<phone;
}
};
void main()
{
Student student1;
student1.accept();
student1.display();
}
ACTIVITY 2B
Program to display the area of the rectangle
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab2B.cpp.
#include <iostream.h>
class Rectangle
{
private:
double l,w,a;
public:
void accept();
void area();
void display();
};
void Rectangle :: accept()
{
cout<<"\nEnter the length : ";
cin>>l;
cout<<"Enter the width : ";
cin>>w;
}
void Rectangle :: area()
{
a= l*w;
8
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
ACTIVITY 2C
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab2C.cpp.
#include <iostream.h>
class Student
{
private:
// class data member
int idNum;
double cgpa;
public:
void SetData (int, double);
void ShowData();
// End of class declaration
};
void Student :: void SetData (int id, double result)
{
idNum = id;
9
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
cgpa = result;
}
void Student :: void ShowData()
{
cout << “Student id is “ << idNum << endl;
cout << “CGPA is “ << cgpa << endl;
}
// Object declaration
void main()
{
Student S1, S2;
S1.SetData (1234, 3.34);
S2.SetData (9584, 3.78);
S1.ShowData();
S2.ShowData();
}
EXERCISE
1. Write a program using classes and objects to add two numbers of integer data type.
[5M]
2. Write a program using classes and objects for Circle. The program should accept
the radius and calculate the area and perimeter of the circle. The program should
display the radius, area and perimeter.
[5M]
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
10
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Use constructor in programs
2. Use destructor in programs
THEORY
11
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
class vehicle
{
Example:
public:
vehicle();
}
Constructor
Constructo
r
The constructor allocates sufficient memory space
for the object.
Types of constructor:
Default constructor
Parameterized constructor.
Initialization constructor.
Copy constructor.
Overloading constructor
12
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
class vehicle
{
Example:
public:
vehicle();
~vehicle(); Destructor
};
ACTIVITY 3A
Default Constructor
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab3A.cpp.
#include<iostream.h>
class rectangle {
private:
int length, width, area;
public:
rectangle ( ){ }; // constructor lalai
// default constructor
void input_data(int a, int b)
{ length= a;
width = b; }
int calculate_area()
{ return length * width;}
};
main()
{ rectangle s;
13
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
int a,b;
cout<<"Length: ";
cin>>a;
cout<<"Width: ";
cin>>b;
s.input_data(a,b);
cout<<"The area of rectangle is: "<<s.calculate_area();
return 0;
}
ACTIVITY 3B
Parameterized Constructor
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab3B.cpp.
#include<iostream.h>
class Rectangle{
int length,width;
public:
Rectangle(int a, int b):length(a),width(b){}
int calculate_area()
{return length * width;}
};
void main()
{
int m,n;
cout<<"The value of m:";
cin>>m;
cout<<"The value of n:";
cin>>n;
Rectangle a(m,n);
cout<<"The area of a rectangle is: "<<a.calculate_area()<<endl;
}
ACTIVITY 3C
Initialization Constructor
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab3C.cpp.
14
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
#include<iostream.h>
class Rectangle{
int length,width;
public:
Rectangle():length(10),width(20){}
int calculate_area()
{
return length * width; }
};
void main()
{
Rectangle a;
cout<<"The area of rectangle is: "<<a.calculate_area();
}
ACTIVITY 3D
Copy Constructor
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab3D.cpp.
#include<iostream.h>
class Rectangle{
int length,width;
public:
Rectangle(int a, int b):length(a),width(b){}
int calculate_area()
{return length * width;}
};
void main()
{
int m,n;
cout<<"The value of m:";
cin>>m;
cout<<"The value of n:";
cin>>n;
Rectangle Z(m,n);
Rectangle A(Z);
cout<<"The area of a rectangle is:"<<A.calculate_area()<<endl;
}
15
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Or
#include<iostream.h>
class Rectangle{
int length,width;
public:
Rectangle(){};
Rectangle(int a, int b):length(a),width(b){}
int calculate_area()
{return length * width;}
};
void main()
{ Rectangle A;
int m,n;
cout<<"The value of m:";
cin>>m;
cout<<"The value of n:";
cin>>n;
A=Rectangle(m,n);
cout<<"The area of a rectangle is: "<<A.calculate_area()<<endl;
}
ACTIVITY 3E
Overloading Constructor
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab3E.cpp.
#include<iostream.h>
class square
{
int length ;
public:
square ( ) { length = 5; }
square ( int n ) { length=n;}
int area(){return length * length;}
};
int main()
{
square o1(10); // isytiharkan objek dengan nilai awalan
// declare object with initialized value
square o2; // isytiharkan tanpa nilai awalan
// a declaration without a initialized value
cout<<"o1: "<<o1.area()<<'\n';
cout<<"o2: "<<o2.area()<<'\n';
return 0;
}
16
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
ACTIVITY 3F
Constructor and Destructor
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab3F.cpp.
#include <iostream.h>
class Student
{
public:
Student() // Constructor
{
cout <<“Define Constructor and memory allocated to the object!!” << endl;
}
~Student() // Destructor
{
cout << “Define Destructor and object is destroyed(memory
reclaim)!!”<<endl;
}
}; // End of class declaration
void main()
{
Student S1; // Define object
}
ACTIVITY 3G
Program using constructor and destructor with inheritance, between constructor
and destructor in base and derived class, which will call first.
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab3G.cpp.
#include <iostream.h>
#include <iostream.h>
class base {
public :
base() {cout <<“Constructing base \n’;}
~base(){cout <<“Destructing base \n”;}
};
class derived : public base{ //class derived inherit from class base
public:
derived(){cout <<“Constructing derived \n”;}
~derived(){cout <<“Destructing derived \n”;}
17
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
};
int main(){
derived ob;
return 0;
}
EXERCISE
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
18
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LAB 4: FRIEND
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Create a method or function of non-member as a friend
THEORY
Friend
ACTIVITY 4A
Function as a friend
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab4A.cpp.
19
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
# include <iostream.h>
class staff
{
int hour;
double rate;
public:
staff(int a, double b){hour=a, rate=b;}
};
double calculate_OT(staff y)
{ return y.hour * y.rate;}
void main()
{
int x;
double y;
cout<<" Total Hours: ";
cin>>x;
cout<<" Hourly Rate : ";
cin>>y;
staff a(x,y);
cout<<"Total Payment : "<<calculate_OT(a)<<endl;
}
ACTIVITY 4B
Class as a friend
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab4B.cpp.
#include <iostream.h>
#include <string.h>
class Point;
class Information
{
friend class Point;
private:
char name[30],id[10];
public:
void setdata(char *,char *);
20
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
};
class Point
{
int cumulated_point,current_point,total_point;
public:
void set_point(int,int);
void calculate_point();
void display(Information);
};
void Point::calculate_point()
{ total_point=cumulated_point + current_point;}
void Point::display(Information a)
{
cout<<"Member's Name :"<<a.name<<"\n";
cout<<"ID :"<<a.id<<"\n";
cout<<"Total Point :"<<total_point<<"\n";
if (total_point> 1000)
cout<<"Qualified to be VIP Member.";
else
cout<<"Not qualified to be VIP Member.";
cout<<'\n';
}
void main()
{
char name[30],id[10];
int cumulated_point,current_point;
Point a;
Information b;
cout<<"Name:";
cin.getline(name,30);
cout<<"ID :";
cin.getline(id,10);
cout<<"Cumulated Point :";
cin>>cumulated_point;
cout<<"Current Point :";
cin>>current_point ;
cout<<'\n';
b.setdata(name,id);
21
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
a.set_point(cumulated_point,current_point);
a.calculate_point();
a.display(b);
}
EXERCISE
1. Build a program that can calculate the volume of box. This program has 2 functions,
which are function for assigning values of length, width and depth and function for
counting a volume of box. Use the friend concept in the function to calculate the
volume of box. Below is the formula to count a volume of box.
[5M]
[10M]
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
22
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Create overloaded method based on program situation.
THEORY
Is a mechanism wh 23
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
ACTIVITY 5A
Method Overloading
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab5A.cpp.
24
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
#include<iostream.h>
#include<string.h>
class Student{
char name[30];
int age;
char ic[30];
public:
void setdata(char *a,char * c)
{
strcpy(name,a);
strcpy(ic,c);
}
void setdata(int b)
{age=b;}
void showdata()
{
cout<<"Name:"<<name<<"\n";
cout<<"IC:"<<ic<<"\n";
cout<<"Age:"<<age<<"\n";
}
};
void main()
{
char name[30];
int age;
char ic[30];
Student a;
a.setdata(name,ic);
a.setdata(age);
a.showdata();
}
ACTIVITY 5B
Overloading Operator
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab5B.cpp.
25
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
#include<iostream.h>
class choose{
public:
int x, y;
choose(){};
choose(int a)
{x=a;;}
choose operator +(choose param)
{
choose answer;
answer.x=x+param.x;
return (answer);
}
choose operator -(choose param)
{
choose answer;
answer.x=x-param.x;
return (answer);
}
choose operator *(choose param)
{
choose answer;
answer.x=x*param.x;
return (answer);
}
};
void main()
{
int a,b;
cout<<"First number:";
cin>>a;
cout<<"Second number:";
cin>>b;
choose obj1(a);
choose obj2(b);
choose obj3,obj4,obj5;
obj3=obj1+obj2;
obj4=obj1-obj2;
obj5=obj1*obj2;
cout<<"The result of addition "<<a<<" and "<<b<<"="<<obj3.x<<"\n";
cout<<"The result of deduction "<<a<<" and "<<b<<"="<<obj4.x<<"\n";
cout<<"The result of subtrction "<<a<<" and "<<b<<"="<<obj5.x<<"\n";
}
EXERCISE
26
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
1. Create a program to calculate the average of integers and doubles. This program
has one class called number. In this class, there is an average() function that
calculates the average where it uses the overloading function concept . Below is the
example of an average() function that should be in the program.
void average(int x, int y, int z );
void average (double a,double b);
[5M]
2. Build a program to get the coordinat value using binary(++) operator. This program
should have two constructor which is default constructor that will initialize the value x
and y=0, while parameterized constructor will set the value according to object
instantiation. There is get_xy(int &i, int&j) function that will send the value of x and y
to i and j. Operator overloading will add the object and display it.
[5M]
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
27
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LAB 6: TEMPLATE
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Write a program using templates.
THEORY
28
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Generic
function
29
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
ACTIVITY 6A
Generic functions
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab6A.cpp.
#include <iostream.h>
template <class segi4>
void luas(segi4 panjang, segi4 lebar)
{ segi4 segi;
segi= panjang * lebar;
cout<<segi<<'\n';
}
void main(){
int i=10,j=20;
double y=10.1,z=4.2;
cout<<"Panjang (dalam nilai integer): "<<i<<'\n';
cout<<"Lebar (dalam nilai integer): "<<j<<'\n';
cout<<"Luas segiempat dalam nilai integer: "luas(i,j);
cout<<"Panjang (dalam nilai double): "<<y<<'\n';
cout<<"Lebar (dalam nilai double): "<<z<<'\n';
cout<<"Luas segiempat dalam nilai double: ";
luas (y,z);
}
ACTIVITY 6B
Generic class
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab6B.cpp.
#include <iostream.h>
template<class type1>
class Bentuk {
type1 u1, u2, pilihan, luas;
30
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
public:
Luas(type1 ,type1 ,type1 );
};
template<class type1>
Bentuk<type1>::Luas(type1 pilihan,type1 u1,type1 u2){
if (pilihan ==1) {
luas=u1 * u2;
cout<<"luas segiempat: "<<luas<<’\n’;
}
if(pilihan ==2) {
luas = ((u1*u2) /2);
cout<<"luas segitiga: "<<luas<<’\n’;
}
}
void main()
{
int ukur1,ukur2,pilihan;
char terus;
Bentuk<double> segi3;
Bentuk<double> segi4;
cout<<"Pilih 1 utk mengira luas segiempat\n";
cout<<"Pilih 2 utk mengira luas segitiga\n";
do{
cout<<"Pilihan anda: ";
cin>>pilihan;
switch(pilihan){
case 1: {
pilihan = 1;
cout<<"nilai lebar: ";
cin>>ukur1;
cout<<"nilai tinggi: ";
cin>>ukur2;
segi4.Luas(1,ukur1,ukur2);
break;
}
case 2:{
pilihan= 2;
cout<<"nilai tapak: ";
cin>>ukur1;
cout<<"nilai tinggi: ";
cin>>ukur2;
cout<<"Luas segitiga ";
segi3.Luas(2,ukur1,ukur2);
break;
}
}
cout<<" Mahu membuat pengiraan lain? (Y/N) \n";
31
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
cin>>terus; }
while (terus=='Y'||terus=='y');
}
EXERCISE
1. Create a program, which can calculate the total price that a member and non-
member of a direct selling company has to pay. Use the generic class concept to
calculate the total payment to be made. The formula to calculate the total price is
shown below:
Member
TOTAL PRICE = (price per unit – (0.2 * price per unit)) * quantity
Non-member
[10M]
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
32
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LAB 7: INHERITANCE
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Create derived class from a base class and multiple base classes
THEORY
Inheritan
ce
33
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Advantages of inheritance
Code reusability
ACTIVITY 7A
Single Inheritance
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab7A.cpp.
#include <iostream.h>
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
34
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
{ width=a; height=b;}
};
int main () {
CRectangle rect;
CTriangle trgl;
rect.set_values (4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
ACTIVITY 7B
Single Inheritance
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab7B.cpp.
#include <iostream.h>
class Student
{
protected:
long StudentID;
public:
35
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
void GetStudentID();
};
class Result : public Student
{
private:
float Marks;
public:
void GetMarks();
void Display();
};
void Student :: GetStudentID()
{
cout << “Enter Student ID : “;
cin >> StudentID;
}
void Result :: GetMarks()
{
cout << “Enter Marks : “;
cin >> Marks;
}
void Result :: Display()
{
GetStudentID();
GetMarks();
cout << “\nStudentID : “ << StudentID << endl;
cout << “Marks : “ << Marks << endl;
}
void main()
{
Result R; // R is object of Result class
R.Display();
}
ACTIVITY 7C
Multiple Inheritance
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab7C.cpp.
36
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
#include <iostream.h>
class Academic
{
public:
long int StudentID;
void GetStudentIID();
};
class Result
{
private:
float Marks;
public:
void GetMarks();
};
// class Student – derived class
class Student : private Academic, public Result
{
public:
void Display();
};
void Academic :: GetStudentID()
{
cout << “Enter Student ID : “;
cin >> StudentID;
cout << endl << “Student ID : “ << StudentID << endl;
}
void Result :: GetMarks()
{
cout << endl << “Enter Marks : “;
cin >> Marks;
cout << endl << “Marks : “ << Marks << endl;
}
void Student :: Display()
{
GetStudentID();
GetMarks();
}
void main()
{
Student SIT, DIP;
SIT.Display();
DIP.Display();
}
37
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
EXERCISE
1. Write a C++ program that accepts price of an item in the base class Item.
In the derived class Quantity, the number of items is accepted from the user and
the total price should be calculated. The program should also calculate the total
price of the items after a discount of 15% on the total price.
[5M]
2. Write a C++ program that accepts the customer id in the base class
Customer. In the derived class GoldMember, the purchase amount is accepted
from the user. If the amount is greater than RM 500 , then RM 100 is deducted on
the amount purchased else only RM 50 is deducted. The program should display
the amount.
[5M]
float amount
char id float deduction
get () accept()
display()
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
38
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Implement the overriding and abstract classes.
THEORY
1. Abstract classes act as expressions of general concepts from which more specific
classes can be derived.
2. Object cannot be create for abstract class type.
3. However, pointers and references to abstract class types can be used.
4. A class that contains at least one pure virtual function is considered an abstract class.
5. Classes derived from the abstract class must implement the pure virtual function or it
also consider as abstract classes.
6. Virtual member functions are inherited.
7. A class derived from an abstract base class will also be abstract unless you override
each pure virtual function in the derived class.
ACTIVITY 8A
Abstract class
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab8A.cpp.
#include <iostream.h>
class Shape {
protected:
int length, width;
public:
void set_value (int a, int b)
{ length=a; width=b; }
virtual void area()
{ cout<<"No calculation for area here\n";}
};
class Rectangle: public Shape {
public:
void area ()
{ cout<<"The area of rectangle is ";
39
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
cout<<length*width<<endl; }
};
class Triangle: public Shape {
public:
void area ()
{ cout<<"The area of triangle is ";
cout<<(length * width)/2<<endl; }
};
void main ()
{
int length, width;
Shape * b;
Rectangle four;
Triangle three;
cout<<"Enter length:";
cin>>length;
cout<<"Enter width:";
cin>>width;
b=&four;
b->set_value(length, width);
b->area();
b=&three;
b->set_value(length,width);
b->area();
}
ACTIVITY 8B
Pure virtual function.
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab8B.cpp.
#include <iostream.h>
class Shape {
protected:
int length, width;
public:
void set_value (int a, int b)
{
length=a;
width=b;
}
virtual void display()=0;
};
class Rectangle: public Shape {
int area;
40
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
public:
void calculate_area ()
{
area=length*width;
}
void display()
{
cout<<"The area of Rectangle is="<<area<<endl;
}
};
class Triangle: public Shape {
int area;
public:
void calculate_area ()
{
area=(length * width)/2;
}
void display()
{
cout<<"The area of Triangle is="<<area<<endl;
}
};
void main () {
ACTIVITY 8C
Pure virtual function.
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab8C.cpp.
41
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
#include<iostream.h>
#include<string.h>
class person{
protected:
char name[30];
int age;
public:
void setdata(char * a, int b)
{
strcpy(name,a);
age=b;
}
virtual void display()=0
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age<<endl;
}
};
class staff:public person{
double salary;
public:
void set_salary(double a)
{
salary=a;
}
void display()
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age<<endl;
cout<<"Salary:"<<salary<<endl;
}
};
void main()
{
person *p;
staff a;
p=&a;
p->setdata("Ali bin Abu",24);
a.set_salary(1500.00);
p->display();
}
EXERCISE
1. Create a program, which can calculate the volume of cylinder and cube from the
abstract class shape. Use the pure virtual function concept to calculate the volume.
The formula to calculate the volume is shown below:
42
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
Cylinder = pi r2 h
Cube = length * width * height
[10M]
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
43
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LAB 9: POLYMORPHISM
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Implement the polymorphism.
THEORY
1. Poly, referring to many, signifies the many uses of these operators and functions.
2. Polymorphism is the ability to use an operator or function in different ways.
3. Polymorphism gives different meanings or functions to the operators or functions.
4. A single function usage or an operator functioning in many ways can be called
polymorphism.
5. Polymorphism refers to codes, operations or objects that behave differently in different
contexts.
ACTIVITY 9A
Polymorphism
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab9A.cpp.
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b) {
width=a;
height=b;
}
virtual int area () =0;
void printarea (void) {
cout << this->area() << endl;
44
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
}
};
class CRectangle: public CPolygon {
public:
int area (void) {
return (width * height);
}
};
ACTIVITY 9B
Overloading function
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab9B.cpp.
#include <iostream.h>
void RepeatChar ();
void RepeatChar (char);
void RepeatChar (char, int);
int main()
{
RepeatChar ();
RepeatChar (‘=’);
RepeatChar (‘+’, 30);
return 0;
}
void RepeatChar ()
{
for (int j=0; j<45; j++)
cout << “* \t”; // always prints *
cout << endl;
}
void RepeatChar (char ch)
{
for (int j=0; j<45; j++)
cout << ch << “\t”; // prints specified char
cout << endl;
}
45
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
ACTIVITY 9C
Polymorphism
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab9C.cpp.
#include <iostream.h>
void main()
{
int j, k, l, m, n, p, q;
q = 4; j = 6;
k = Addition (q, j);
cout << endl << “Sum of two is “ << k << endl;
l = 5; m = 6; n = 7;
p = Addition (I, m, n);
cout << endl << “Sum of three is “ << p << endl;
}
ACTIVITY 9D
Polymorphism
Procedure:
Step 1: Type the programs given below
46
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
#include <iostream.h>
int x, y;
cout << “Enter two integers <x & y> :”;
cin >> x >> y;
Swap (x, y);
cout <<”After swapping <x, y> : “ << x << “\t” << y <<
endl;
double m, n;
cout << “Enter two doubles <m & n> :”;
cin >> m >> n;
Swap (m, n);
47
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
cout <<”After swapping <m, n> : “ << m << “\t” << n <<
endl;
}
EXERCISE
1. Create a program, which can calculate the average of numbers. Use the overloading
concept which there will be two function average(double n1, double n2) and
average(int n1, int n2, int n3).
[5M]
2. Write a program that can perform addition that applied overloading function in
polymorphism. Addition function has two forms, in one form it has two integer type
parameters and the other it has two double type parameters
[5M]
NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
48
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Implement the exceptions handling.
THEORY
1. The concept is to raise some error flag every time something goes wrong. Next,
there is a system that is always on the lookout for this error flag. Finally, the previous
system calls the error handling code if the error flag has been spotted.
2. Exception handling is designed to process synchronous errors, which occur when a
statement executes.
3. Common examples of these errors are out-of-range array subscript, arithmetic
overflow, division by zero, invalid function parameters and unsuccessful memory
allocation.
4. Exception handling is not designed to process errors associated with asynchronous
events, which occur in parallel with and independent of the program’s flow of control.
try
{
...
...
throw Exception()
...
...
}
catch( Exception e )
{
...
...
}
49
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
ACTIVITY 10A
Exception Handling
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab10A.cpp.
#include <iostream>
using namespace std;
int main ()
{
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << endl;
}
return 0;
}
ACTIVITY 10B
Exception Handling
Procedure:
Step 1: Type the programs given below
Step 2: Compile and run the program. Write the output.
Step 3: Save the program as lab10B.cpp.
#include<iostream>
#include <exception>
using namespace std;
50
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
EXERCISE
1. Write a program that ask the user to enter one integer type number. If the input
number is a positive number (1 and above), it will print a message ”Input number is a
positive number”. If not an exception (exception &) will be thrown and it will print a
message "Exception occured : Not a positive number." Use stdexcept as header
file. Output display shown as below.
Enter a number : -7
Exception occured : Not a positive number.
[5M]
NOTES
________________________________________________________________________
________________________________________________________________________
51
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
52