63
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

F3031 Lab Workbook

  • Upload
    f3031

  • View
    630

  • Download
    2

Embed Size (px)

Citation preview

Page 1: F3031 Lab Workbook

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

Page 2: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 1: INTRODUCTION TO OOP

LEARNING OUTCOMESBy 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

Page 3: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

ACTIVITY 1Procedure: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 NasruddinRegs. Number : 01DIT07F2345Course : Object Oriented ProgrammingMark: 80Gred: A

3

4 Main concepts of OOP

Data abstraction: is a process to

delete all unnecessary attributes and

remain the necessary attributes to

describe an object.

Encapsulation: is a process of tying

together all data and methods that

form a class and control the access to

data by hiding its information.

Inheritance: Create a new class from

an existing class together with new

attributes and behaviors.

Polymorphism: Polymorphism is

processes of giving the same message to

another two or more different objects

and produce different behaviors depend

on how the objects receive the message.

Page 4: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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

Staff_No Name Gender IC NO Address Telephone.No Start Working(Year)

A0410 Lina Bt Kassim F 750514-02-5843 No.1 Jalan Batu Berendam, Melaka

014-2233678 2000

A8092 Budi Bin Bidin M 681223-03-5777 PT 32, Jalan Kemaman,Kuala Lumpur

0135678999 1994

Page 5: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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: 2000Total 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

Page 6: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

LAB 2: CLASS AND OBJECT

LEARNING OUTCOMESBy 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

Page 7: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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 2AProgram to display the student's detailsProcedure:Step 1: Type the programs given belowStep 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

Page 8: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

void display()

{

cout<<"\n Student\'s name : "<<name;

cout<<"\n Phone number : "<<phone;

}

};

void main()

{

Student student1;

student1.accept();

student1.display();

}

ACTIVITY 2BProgram to display the area of the rectangle Procedure:Step 1: Type the programs given belowStep 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

Page 9: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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 2CProcedure:Step 1: Type the programs given belowStep 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

Page 10: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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

Page 11: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 3: CONSTRUCTOR AND DESTRUCTOR

LEARNING OUTCOMESBy the end of this lab, students should be able to :1. Use constructor in programs2. Use destructor in programs

THEORY

11

Page 12: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

12

Constructor

A constructor is a method that is called each time an object is created.

A constructor has the same name as the class name.

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

Example:

Constructor

class vehicle { public:

vehicle();}

class vehicle { public:

vehicle();}

Page 13: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

ACTIVITY 3ADefault ConstructorProcedure:Step 1: Type the programs given belowStep 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

Destructor A destructor is a method called automatically when an

object is destroyed or goes out of scope.

A destructor has the same name as the class, but it has

a tilde(~) infront of it.

Example:

class vehicle{ public:

vehicle();~vehicle();

}; Destructor

Destructor does not return a value.

Arguments cannot be sent to a destructor

Page 14: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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 3BParameterized ConstructorProcedure:Step 1: Type the programs given belowStep 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 3CInitialization ConstructorProcedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab3C.cpp.

14

Page 15: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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 3DCopy ConstructorProcedure:Step 1: Type the programs given belowStep 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

Page 16: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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 3EOverloading ConstructorProcedure:Step 1: Type the programs given belowStep 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 valuesquare o2; // isytiharkan tanpa nilai awalan

// a declaration without a initialized valuecout<<"o1: "<<o1.area()<<'\n';cout<<"o2: "<<o2.area()<<'\n';return 0;}

16

Page 17: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

ACTIVITY 3FConstructor and DestructorProcedure:Step 1: Type the programs given belowStep 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 declarationvoid main(){Student S1; // Define object}

ACTIVITY 3GProgram 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 belowStep 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 basepublic:derived(){cout <<“Constructing derived \n”;}~derived(){cout <<“Destructing derived \n”;}

17

Page 18: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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

Page 19: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 4: FRIEND

LEARNING OUTCOMESBy the end of this lab, students should be able to :1. Create a method or function of non-member as a friend2. Create classes as a friend

THEORY

ACTIVITY 4AFunction as a friendProcedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab4A.cpp.

19

Friend

2 ways to declare friend function:

i. Declaring function as friend

ii. Declaring class as friend.

The keyword friend should be placed in front of the function or class that is being declared as friend.

Friend function is declared under the access

control public.

When declaring a class as a friend, the declaration

should be done in the prototype section

Page 20: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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 4BClass as a friendProcedure:Step 1: Type the programs given belowStep 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

Page 21: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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.";

elsecout<<"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);a.set_point(cumulated_point,current_point);

21

Page 22: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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]

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.

[10M]

NOTES________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

22

VOLUME = length * width * depth

Output

Page 23: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 5: METHOD AND OPERATOR OVERLOADING

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

THEORY

23

Overloading function

Is a mechanism which

allows 2 or more

related function to

share name but with

different parameter

declaration.

Applies polymorphism

concept

Rules of overloading function

2. The type of the parameter must be different

1. The amount a parameter received is

different for each function.

Operator overloading Similar to function

overloading.

When an operator is overloaded the original

meaning would not lost and it will have added

meaning to the class, which defines it.

Operator overloading uses operator

function

General syntax for operator function

Return type class-name :: operator # (list of argument)

{ // body of the function

}

The overloading function can

reduce the difficulty of a program

by allowing operation to be

referred with the same name.

The overloading function can

reduce the difficulty of a program

by allowing operation to be

referred with the same name.

Page 24: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

ACTIVITY 5AMethod OverloadingProcedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab5A.cpp.

24

Using member to overload unary operators

Same as overloading

binary operator Only uses one operand

When the unary operator is

overloaded using the

members’ function, this

function could not accept

parameter because it

involves only one operand.

2 limitations during the process of operator overloading

Precedence of the

operator cannot be

changed

The number of operand

cannot be changed

Rules in overloading

operators

Operator function cannot contain

default arguments

Operators that cannot be overloaded

. :: .* ? preprosesor operator

Page 25: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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 5BOverloading OperatorProcedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab5B.cpp.

25

Page 26: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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

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

26

Page 27: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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

Page 28: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 6: TEMPLATE

LEARNING OUTCOMESBy the end of this lab, students should be able to :1. Write a program using templates.

THEORY

28

Template

Is a frame or a form that is use to generate

a function or a class.

One of the way to achieve polymorphism

Allows the programmer to generate

generic function and generic class.

Generic Function: Generic function is a

draft for a function that can be used to

generate a few same functions in different

version.

Generic Class: Generic class is used to

generate new classes in different version

Advantage of template

Codes are shorter

and easier to

understand

New classes can be

generated without

redefining the definition

Page 29: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

29

Generic function

Syntax for declaring generic function

template <class Data_Type> Function_Name( ) { //function body }

If there is more than 1 generic data type, use a

comma (,) to separate each of them.

Example:

template <class count1, class count2> When a generic function is called, the arguments

will determine the type of data that will be used in

the function.

Generic function must do the same action for all version - only the data types can be different

Generic class Generic class is useful for classes using logic

that can be made as general conclusion.

The compiler will automatically generate

the object according to the data type

specified when the object is created.

Syntax for declaring generic class:

template <class DataType> class Class_Name

{ :

:

}

Syntax for declaring an object:

Class_Name <DataType> Object_Name;

Can consist of more than

one generic data type.

Page 30: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

ACTIVITY 6AGeneric functionsProcedure:Step 1: Type the programs given belowStep 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 6BGeneric classProcedure:Step 1: Type the programs given belowStep 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; public:

Luas(type1 ,type1 ,type1 );};

template<class type1>

30

Page 31: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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";cin>>terus; }while (terus=='Y'||terus=='y');

}

31

Page 32: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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

Non-member

[10M]

NOTES________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

32

TOTAL PRICE = (price per unit – (0.2 * price per unit)) * quantity

TOTAL PRICE = price per unit * quantity

Page 33: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 7: INHERITANCE

LEARNING OUTCOMESBy the end of this lab, students should be able to :1. Create derived class from a base class and multiple base classes

THEORY

33

Inheritance

Similar to the biology concept where children usually inherit

their parent’s characteristics.

2 types of class

Syntax for defining a derived class.

class Derived_class: acess_specifier Base_class{

// body of derived class};

1. Base class: A class where it allows its data members and member functions to be inherited by other classes

2. Derived class: A class, which inherits from

the base class.

Page 34: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

ACTIVITY 7ASingle InheritanceProcedure:Step 1: Type the programs given belowStep 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)

{ width=a; height=b;}

};

34

Advantages of inheritance

Code reusability

It allows the use of access control:

private, protected and public

Organize objects into hierarchies

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.

Page 35: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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 7BSingle InheritanceProcedure:Step 1: Type the programs given belowStep 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:

void GetStudentID();

};

35

Page 36: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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 7CMultiple InheritanceProcedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab7C.cpp.

36

Page 37: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

#include <iostream.h>class Academic{ public:

long int StudentID;void GetStudentIID();

};class Result{ private:

float Marks; public:

void GetMarks();};// class Student – derived classclass 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

Page 38: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

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

char idfloat amount

float deduction

get () accept()display()

NOTES________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

38

Page 39: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 8: OVERRIDING AND ABSTRACT CLASS

LEARNING OUTCOMESBy the end of this lab, students should be able to :

1. Implement the overriding and abstract classes.

THEORY1. 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 8AAbstract classProcedure:Step 1: Type the programs given belowStep 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 ";

cout<<length*width<<endl; } };

39

Page 40: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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 8BPure virtual function.Procedure:Step 1: Type the programs given belowStep 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;public: void calculate_area ()

40

Page 41: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

{ 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 8CPure virtual function.Procedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab8C.cpp.

#include<iostream.h>

41

Page 42: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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

42Cylinder = pi r2 h

Cube = length * width * height

Page 43: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

[10M]

NOTES________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

43

Page 44: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 9: POLYMORPHISM

LEARNING OUTCOMESBy the end of this lab, students should be able to :1. Implement the polymorphism.

THEORY1. 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 9APolymorphismProcedure:Step 1: Type the programs given belowStep 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

Page 45: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

class CRectangle: public CPolygon {

public:

int area (void) {

return (width * height);

}

};

ACTIVITY 9BOverloading functionProcedure:Step 1: Type the programs given belowStep 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) {

for (int j=1; j<=n; j++) // loops n timescout << ch << “\t”; // prints the char

cout << endl;

45

Page 46: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

}

ACTIVITY 9CPolymorphism Procedure:Step 1: Type the programs given belowStep 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 9DPolymorphism Procedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab9D.cpp.

46

Page 47: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

#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); cout <<”After swapping <m, n> : “ << m << “\t” << n << endl;}

47

Page 48: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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

Page 49: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

LAB 10: EXCEPTION HANDLING

LEARNING OUTCOMESBy 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 ){     ...     ...}

ACTIVITY 10AException HandlingProcedure:

49

Page 50: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

Step 1: Type the programs given belowStep 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 10BException HandlingProcedure:Step 1: Type the programs given belowStep 2: Compile and run the program. Write the output.Step 3: Save the program as lab10B.cpp.

#include<iostream> #include <exception> using namespace std;

class myexception: public exception {

virtual const char* what() const throw() {

return "My exception happened"; }

50

Page 51: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

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

[5M]

NOTES________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

51

Enter a number : 120Input number is a positive number.

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

Page 52: F3031 Lab Workbook

F3031 OBJECT ORIENTED PROGRAMMINGJANUARY

2010

52