Вы находитесь на странице: 1из 52

Table of Content

LAB 1: INTRODUCTION TO OOP.....................................................................................................2


LAB 2: CLASS AND OBJECT.............................................................................................................6
LAB 3: CONSTRUCTOR AND DESTRUCTOR..............................................................................11
LAB 4: FRIEND..................................................................................................................................19
LAB 5: METHOD AND OPERATOR OVERLOADING.................................................................23
LAB 6: TEMPLATE............................................................................................................................28
LAB 7: INHERITANCE......................................................................................................................33
LAB 8: OVERRIDING AND ABSTRACT CLASS..........................................................................39
LAB 9: POLYMORPHISM.................................................................................................................44
LAB 10: EXCEPTION HANDLING..................................................................................................49
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

LAB 1: INTRODUCTION TO OOP

LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Define OOP

THEORY

• Classes, Object, Encapsulation, Data Abstraction, Inheritance and Polymorphism is


a basic terminologies in Object Oriented programming

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 :

Name: Najjah Bt Nasruddin


Regs. Number : 01DIT07F2345
Course : Object Oriented Programming
Mark: 80
Gred: A

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]

Staff_No Name Gender IC NO Address Telephone.No Start


Working(Year)

A0410 Lina Bt Kassim F 750514-02-5843 No.1 Jalan 014-2233678 2000


Batu
Berendam,
Melaka

A8092 Budi Bin Bidin M 681223-03-5777 PT 32, Jalan 0135678999 1994


Kemaman,
Kuala Lumpur

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:

Name: Lina Bt Kassim


Start Working: 2000
Total year: 9

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

________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________

LAB 2: CLASS AND OBJECT

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

• Classes: Definition – is a collection of similar objects, which share common


attributes and methods.
• A class is a blue print or prototype defining the variables and methods common to all
objects of a certain kind.
• Objects are members of classes. An Object consists of data and method. An object is
an instance of a certain class. A class variable is called a class object or class instance.
Note: After you have created a class, you must create an instance of it before you can
use.

6
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

The general syntax for defining a class is

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

cout<<"\nArea of rectangle is : "<<a;


}
void Rectangle :: display()
{
cout<<"\n Length is : "<<l;
cout<<"\n Width is : "<<w;
}
void main()
{
Rectangle obj;
cout<<"\nEnter the details\n";
obj.accept();
cout<<"\nThe details\n";
obj.display();
obj.area();
}

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

LAB 3: CONSTRUCTOR AND DESTRUCTOR

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

A constructor is a method that is called each time an


object is created.

A constructor has the same name as the class name.

class vehicle
{
Example:
public:
vehicle();
}
Constructor
Constructo
r
The constructor allocates sufficient memory space
for the object.

A constructor does not return a value, but


arguments can be passed to a constructor.

Types of constructor:
Default constructor
Parameterized constructor.
Initialization constructor.
Copy constructor.
Overloading constructor

12
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

A destructor is a method called


Destructo
automatically when an object is destroyed
r
or goes out of scope.

A destructor has the same name as the


class, but it has a tilde(~) infront of it.

class vehicle
{
Example:
public:
vehicle();
~vehicle(); Destructor
};

Destructor does not return a value.

Arguments cannot be sent to a 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

1. Write a program using overload constructor to calculate the area of square


(length*length) and display it.

I. Initialize the sides of the square=3.


II. User will enter the sides of the square=?
Display I and II.
[5M]
2. Write a program using function constructor(), destructor() and count(). Function
count() is to count the area of rectangle (length =5 ; width =2). Display the output in
function main(). [5M]

3. Write a program to get the output in the figure below :


I. {cout<<"\n Welcome ";} =use either function (constructor @ destructor @
display())
II. { cout<<" TO POLITEKNIK UNGKU OMAR.";}= use either function
(constructor @ destructor @ display() )
III. {cout<<"\n Thank You.\n"; =use either function (constructor @ destructor @
display()) [5M]

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

2. Create classes 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;}

friend double calculate_OT(staff y);

};

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

};

void Information::setdata(char * a,char *b)


{ strcpy(name,a);
strcpy(id,b);
}

class Point
{
int cumulated_point,current_point,total_point;
public:
void set_point(int,int);
void calculate_point();
void display(Information);
};

void Point :: set_point(int point1,int point2)


{ cumulated_point=point1;
current_point=point2;
}

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.

VOLUME = length * width * depth

[5M]

2. Write a program to get the output in the figure below :


IV. There will be two class which is info_student and mark_student. Class
mark_student will be friend to a class info_student.
V. Class info_student will have name and ic with data type character as a
variable. It also have function set_data that accept two variable above as a
pointer in the parameter list.
VI. While mark_student will have mark1, mark2 and total with data type float. The
function is setmark, calculateMark and display.
Output

[10M]

NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
22
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

LAB 5: METHOD AND OPERATOR OVERLOADING

LEARNING OUTCOMES
By the end of this lab, students should be able to :
1. Create overloaded method based on program situation.

2. Create overloaded operator

THEORY

The overloading function can


reduce the difficulty of a program
by allowing operation to be
referred with the same name.

Is a mechanism wh 23
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

Operators that cannot be overloaded


. :: .* ? preprosesor operator

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];

cout<<"Enter your name:";


cin.getline(name,30);

cout<<"Enter your ic:";


cin.getline(ic,30);
cout<<"Enter your age:";
cin>>age;

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

TOTAL PRICE = price per unit * quantity

[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

Similar to the biology concept where children


usually inherit their parent’s characteristics.

1. Base class: A class where it


2 types of allows its data members and
class member functions to be inherited
by other classes

2. Derived class: A class, which


inherits from the base class.

class Derived_class: acess_specifier Base_class


{
Syntax for defining
// body aofderived class.
derived class
};

Inheritan
ce

33
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

Advantages of inheritance

Code reusability

Organize objects into hierarchies

It allows the use of access control:


private, protected and public

Extraction of common properties


from different classes.

When a class is inherited as public , all the protected data


member in the base class will become protected in derived
class and derived class can access and use the protected
data members.

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;}
};

class CRectangle: public CPolygon {


public:
int area ()
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area ()
{ return (width * height / 2); }
};

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]

Class Customer Class GoldMember

float amount
char id float deduction

get () accept()
display()

NOTES
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________

38
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

LAB 8: OVERRIDING AND ABSTRACT CLASS

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 () {

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);
four.calculate_area();
b->display();
b=&three;
b->set_value(length,width);
three.calculate_area();
b->display();
}

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;
}

void RepeatChar (char ch, int n)


{

45
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

for (int j=1; j<=n; j++) // loops n times


cout << ch << “\t”; // prints the char
cout << endl;
}

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>

int Addition (int a, int b)


{
int c = a + b;
return c;
}

int Addition (int d, int e, int f)


{
int g = d + e + f;
return g;
}

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

Step 2: Compile and run the program. Write the output.


Step 3: Save the program as lab9D.cpp.

#include <iostream.h>

void Swap (char &a, char &b)


{
char temp;
temp = a;
a = b;
b = temp;
}

void Swap (int &a, int &b)


{
int temp;
temp = a;
a = b;
b = temp;
}
void Swap (double &a, double &b)
{
double temp;
temp = a;
a = b;
b = temp;
}
void main()
{
char c1, c2;
cout << “Enter two characters <c1 & c2> :”;
cin >> c1 >> c2;
Swap (c1, c2);
cout <<”After swapping <c1, c2> : “ << c1 << “\t” << c2 << endl <<
endl;

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

LAB 10: EXCEPTION HANDLING

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.

Exception handling structure :

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

class myexception: public exception


{
virtual const char* what() const throw()
{
return "My exception happened";
}
}
myex;
int main ()
{
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}

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 : 120


Input number is a positive number.

Enter a number : -7
Exception occured : Not a positive number.

[5M]

NOTES
________________________________________________________________________
________________________________________________________________________
51
JANUARY
F3031 OBJECT ORIENTED PROGRAMMING
2010

________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________

52