Sunteți pe pagina 1din 73

F3031

Object Oriented Programming

CHAPTER 2

CLASSESS AND OBJECTS

By:
PN. NOR ANISAH BINTI MOHD SAAD
CHAPTER 2.0 : CLASSES AND OBJECTS

Understand the concept of Classes and Objects


2.1

Use Constructor in Program


2.2

Use Destructor in Program


2.3

2.4
Create classes and function as a friend

2.5
Create overloaded method and overloaded operator

2.6
Write program using Templates
2.1: UNDERSTAND THE CONCEPT OF
CLASSES AND OBJECTS

1
Define Class

Define
2 Method

3
Access Specifier

4
Declare Objects
1 DECLARE CLASS

General format for defining a class :

class ClassName
{
// Data definition
// Method definition
};

**TIPS**
* Keyword class is a must in defining a class.
* Semicolon (;) must be placed after closing braces each time
you define a class.
1 DECLARE CLASS (CONT.)
Keyword for defining a class
ClassName
Data member definition
class Rectangle
{ int length, width;
public :

Access
void set_data (int x,int y)
control
{ length=x;
width=y;
} Method definition

double calculate_area()
{ return length*width;}
};
2 DECLARE METHOD
There are two ways of defining method :

1. Define it in the class


class Student
{
int ID,age;
char name[30];
double mark;
 
public:
void set_data (int a,int b, char * c, double d)
{
ID=a;
age=b;
strcpy(name,c);
mark=d;
}
};
2 DECLARE METHOD (CONT.)
2. Define it outside the class by using scope resolution operator (::)

class Student
{
int ID,age;
char name[30];
double mark;
 
public:
void set_data (int a,int b,char * c,double d); declare
};
 
void Student::set_data(int a,int b,char * c,double d)
{
ID=a;
age=b;
define
strcpy(name,c);
mark=d;
}
3 ACCESS SPECIFIER

Three type of access specifier for data members and


methods:

1. Public
2. Private
3. Protected
3 ACCESS SPECIFIER
1. Public

 Public members are accessible outside the class (for example


in main() function).
 Members in the class must be declared in the public section to
make it accessible from outside the class.
 Definition of friend does not give any effect to this access control.

class AccessCtrl
{
int value1;
void func1 (long);
int value2;
int func2 (char*);

public :
char* value4;
long func4 ( );
};
3 ACCESS SPECIFIER
2. Private
 Private members can only be achieved by functional members
and friends for a class, which has been declared.
 Example of the use of this keyword in the real world:
The ATM pin number, password to open an e-mail.
 This example is more appropriate if it is declared privately so that it
is not accessed by any other unauthorized person.

class AccessCtrl
{
int value1; Private Data
int value2;
int func2 (char*); Private Method
void func1 (long);
};
3 ACCESS SPECIFIER

1. Protected class A
{ protected:
 Protected members are accessible in int valueA;
the class where it is declared and also };
any other classes, which are inherited class B : public A
from that class. {
 Definition of friend does not give any public:
effect to this access control. void FuncB( );
 Example of the use of this keyword in };
class C : public B
the real world: {
Total savings for a student. public:
 Only certain people knows the actual void FuncC( );
total savings by a student };
such as his/her family members.  
4 DECLARE OBJECTS

Syntax: className
className objectName;
objectName;

 Assuming that you have created an object from the class Student.

 Example of declaration is shown as below:


Student p;

 When an object has been declared, it can be manipulated by any


function, which is declared inside the object class.

 Syntax is used to call a data or method:

ObjectName . MemberName

dot operator
4 DECLARE OBJECTS (CONT.)
2.2: USE CONSTRUCTOR IN PROGRAM

1 Define Constructor

2 Characteristics of Constructor

3 Types of Constructors
(Use Constructors in Program)
1 DEFINE CONSTRUCTOR

1. A constructor is a member (method/function) that is


called automatically each time when an object is created.

2. The constructor allocates sufficient memory space for


the object.

3. C++ will automatically supply a constructor if it is


not supplied.
2 CHARACTERISTICS OF CONSTRUCTOR
Constructor has the same name as the class.
For example constructor for class Employee is declared as:
class Employee Nama kelas
{
public:

Employee ( ); /* pengisytiharan
constructor */ Nama method
}; constructor

The constructor’s task is to built and create object in


memory. However a constructor does not return a value.

An argument can be sent to the constructor

The constructor is called automatically when an object is


created. This means, we don’t have to invoke it like other
functions.
3 TYPES OF CONSTRUCTOR

1.Default Constructor

2.Parameterized Constructor

3.Initialization Constructor

4.Copy Constructor

5.Overloading Constructor
3 TYPES OF CONSTRUCTOR (CONT.)
1.Default Constructor
1. Does not require any value (parameter).
2. Only have to declare the object.
3. C++ will automatically supply a constructor if it is not supplied.
#include<iostream.h>
class box {
private: NOTA
float length, width;
public: Secara automatik,
box ( ); // default pengisytiharan objek ini akan
constructor menyebabkan aturcara
void input( ); memperuntukkan ruang
void area ( ); memori untuk objek box1.
}; Untuk mewujudkan beberapa
void main() objek, kelas harus mempunyai
{ constructor lalai.
box box1; // pengistiharan kelas
}
Method constructor tidak menerima sebarang nilai
3 TYPES OF CONSTRUCTOR (CONT.)
2.Parameterized Constructor

1. A constructor can have many parameters.


2. If the constructor receives a parameter, when the object is created the
parameter must be included with the declaration of the object.

#include<iostream.h>
class SegiEmpat{
int panjang,lebar;
Output
public:
SegiEmpat(int a, int b):panjang(a),lebar(b){}
int kira_luas()
{return panjang * lebar;}
};
void main(){
int m,n;
cout<<"Nilai m:";cin>>m;
cout<<"Nilai n:";cin>>n;
SegiEmpat S(m,n);
cout<<"Luas Segiempat: "<<S.kira_luas()<<endl;
}
3 TYPES OF CONSTRUCTOR (CONT.)
3.Initialization Constructor

1. The value is entered after an argument list for function, starting


with single point ( : )
class SegiEmpat{
protected:
int panjang,lebar;

public:
// method constructor
SegiEmpat ():panjang(10),lebar(20){}
};

· Data panjang akan diberikan nilai 10 manakala nilai data lebar akan diberikan
nilai 20.
· { } masih diperlukan.
3 TYPES OF CONSTRUCTOR (CONT.)
3.Initialization Constructor
The example of a program is to calculate the area of a rectangle based
on the value given on method constructor.

#include<iostream.h>
class SegiEmpat{
int panjang,lebar; Output
public:
SegiEmpat():panjang(10),lebar(20){}

int kira_luas()
{
return panjang * lebar;
}
};
void main()
{
SegiEmpat a;
cout<<”Luas Segiempat:”<<a.kira_luas();
}
3 TYPES OF CONSTRUCTOR (CONT.)
4.Copy Constructor
1. Changing the private data value through a constructor.
SegiEmpat a (1,2); Objek b akan menyalin nilai yang
SegiEmpat b(a); dimiliki oleh objek a
#include<iostream.h>

class SegiEmpat{
int panjang,lebar;
public: Output
SegiEmpat(int a, int b):panjang(a),lebar(b){}
int kira_luas()
{return panjang * lebar;}
};

void main(){
int m,n;
cout<<"Nilai m:";
cin>>m;
cout<<"Nilai n:";
cin>>n;
SegiEmpat S(m,n);
SegiEmpat Z(S);
cout<<"Luas Segiempat: "<<Z.kira_luas()<<endl;
}
3 TYPES OF CONSTRUCTOR (CONT.)
5.Overloading Constructor

1. Just like other methods, constructor can also be


overloaded.

2. You only have to list down all the different version of


constructor needed to be used in the class.

3. The main purpose of overloading a constructor is to


provide options or give the object initial value or not.

4. For example, in the following program, o1 will be


given initial value but not for o2.
3 TYPES OF CONSTRUCTOR (CONT.)
5.Overloading Constructor
The example below shows the calculation of area for a square using the
overloaded constructor.
#include<iostream.h> NOTA
class SegiEmpat_Sama
{
int panjang ; - Sekiranya anda menghapuskan
public: constructor yang mempunyai
SegiEmpat_Sama ( ) { panjang = 5; } senarai argumen yang kosong,
SegiEmpat_Sama ( int n ) { panjang=n;} program tidak akan dikompil
int luas(){return panjang*panjang;} kerana tiada constructor yang
}; sesuai bagi objek yang tidak
int main(){ ditandakan.
SegiEmpat_Sama o1(10); /* isytiharkan - Sekiranya anda menghapuskan
objek dengan nilai awalan */
constructor berparameter, program
tidak akan dikompil kerana ia tidak
SegiEmpat_Sama o2; /* isytiharkan
tanpa nilai Awalan */
sesuai bagi objek yang
cout<<"o1: "<<o1.luas()<<'\n'; ditandakan. Kedua-duanya
cout<<"o2: "<<o2.luas()<<'\n'; diperlukan untuk program ini
return 0; supaya program ini dapat
} dikompilkan dengan betul.
2.3: USE DESTRUCTORS IN PROGRAM

1 Define Destructors

2 Types of Destructors

3 Use Destructors in Program


1 DEFINE DESTRUCTOR

1. The destructor is a function that is called automatically


when an object is destroyed or goes out of scope.

2. The destructor reclaims the memory that is allocated to


the object.
2 CHARACTERISTICS OF DESTRUCTOR

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


a tilde (~) in front of it.

2. A destructor does not return a value.

3. Unlike a constructor, you cannot pass any argument to a


destructor.

4. You cannot have more than one destructor for each


class.

5. A destructor is called automatic when an object goes out


of scope. That means, you don’t have to invoke it like
other functions.
3 USE DESTRUCTORS IN PROGRAM

#include<iostream.h>
class SegiEmpat{
int panjang,lebar;
public:
SegiEmpat();

~SegiEmpat();

int kira_luas()
{
return panjang * lebar;
}
};
void main()
{
SegiEmpat a;
cout<<”Luas Segiempat: ”<<a.kira_luas();
}
2.4: CREATE CLASSES AND FUNCTION AS
A FRIEND

1 Define friend

2 Declare a friend

3 Declaring function as a friend

4 Declaring class as a friend


1 DEFINE FRIEND

1. A function or class can be defined as a friend to other


classes

2. If a function or class becomes the friend to another


class, for example class or function A becomes the
friend to class C, class or function A can access private
member of class C.

3. This concept is considered important to apply if there


is a situation, which we want a class or function wants
to access the private data from the class.
2 DECLARE A FRIEND

1. The declaration for friend can be done through


numerous ways:

I. Declaring function as the friend


II. Declaring class as the friend
 

The keyword friend should be placed in front of the function


or class, which wants to announce as the friend in the class.

For example, if the function calculate() as the friend to Maths


class, so the announcement of a friend should be done in
the Maths class.
3 DECLARING FUNCTION AS A FRIEND

1. By placing the keyword friend in front of the function’s name, the function
can achieve private member of the class. The declaration of friend function
is done in public.
2. The program below stated is an example of the mean for function, which
become friend for staff class.

class pekerja {
// …..
public:
friend void kira_gaji( pekerja a);
//….
}

Example: Function void count_salary();


which has become the friend for the class
staff. By this declaration, this function can
achieve private member; which is staff
class.
3 DECLARING FUNCTION AS A FRIEND

 The example below shows how the calculation of area for the

rectangle is made using friend.


Kelas SegiEmpat
Fungsi
Kira_Luas
Ahli kelas SegiEmpat yang
disimpan ditempat yang sulit
(data-data private)

Pengawal keselamatan akan memeriksa sama ada fungsi Kira_luas berhak


atau tidak mencapai data-data dari kelas SegiEmpat dan jika fungsi
kira_luas diisytiharkan sebagai rakan oleh kelas SegiEmpat, maka ia boleh
mencapai data-data dari kelas SegiEmpat.
3 DECLARING FUNCTION AS A FRIEND
#include<iostream.h>

class SegiEmpat{
int panjang,lebar; Friend function
public: declaration to
SegiEmpat(int a,int b){panjang=a; enable Kira_Luas
lebar=b;} () function to access
member private data
friend int Kira_Luas(SegiEmpat x); from SegiEmpat
}; class.
int Kira_Luas(SegiEmpat x)
{return x.panjang * x.lebar; }

void main()
{int a, b; Defining function
cout<<"Sila masukkan panjang:"; Kira_Luas() that
cin>>a; receive object as
cout<<"Sila masukkan lebar:"; rectangle shows it can
access length and
cin>>b;
width value for the
SegiEmpat tepat(a,b); mentioned object.
cout<<Kira_Luas(tepat);
}
4 DECLARING CLASS AS A FRIEND
1. To make a class as a friend for another class, declaration
of a friend has to be done on a prototype class.
2. Declaration of friend has to been done using keyword
friend.
3. Example below shows how class square was declared as
a friend to class shape.
class bentuk{ Shape class
friend class segiempat; declared class
….. Square as a friend
public: to class Shape. This
…..}; means the class
class segiempat Square can achieve
{ private member for
private: class Shape.
…. .
public:
……};
4 DECLARING CLASS AS A FRIEND
 Below is an example which shows class markah_pelajar becomes
friend to class info_pelajar to enable data member info_pelajar
access data member from class markah_pelajar.

#include <iostream.h> class markah_pelajar{


#include <string.h> float markah1,markah2,jumlah;
public:
class markah_pelajar; void setmarkah(float,float);
void kiraMarkah();
class info_pelajar { void paparan(info_pelajar);
friend class markah_pelajar; };
private:
char nama[30],ic[10]; void
public: markah_pelajar::setmarkah(float
void setdata(char *,char *); ujian1,
}; float ujian2)
void info_pelajar::setdata(char * { markah1=ujian1;
a,char *b) markah2=ujian2;
{ strcpy(nama,a); }
strcpy(ic,b);
}
4 DECLARING CLASS AS A FRIEND (CONT.)
void markah_pelajar::kiraMarkah() void main()
{ {
jumlah=markah1 + markah2; char nama[30],ic[10];
} float markah1,markah2;
void markah_pelajar a;
markah_pelajar::paparan(info_pelajar info_pelajar b;
a) cout<<"Nama:";
{ cin.getline(nama,30);
cout<<"Nama Pelajar:"<<a.nama<<"\n"; cout<<"No KP:";
cout<<"No IC:"<<a.ic<<"\n"; cin.getline(ic,10);
cout<<"Markah Ujian cout<<"Markah Ujian 1:";
1:"<<markah1<<"\n"; cin>>markah1;
cout<<"Markah Ujian cout<<"Markah Ujian 2:";
2:"<<markah2<<"\n"; cin>>markah2;
cout<<"Jumlah cout<<'\n';
Markah:"<<jumlah<<"\n"; b.setdata(nama,ic);
} a.setmarkah(markah1,markah2);
a.kiraMarkah();
a.paparan(b);
}
4 DECLARING CLASS AS A FRIEND (CONT.)

Output
2.5: CREATE OVERLOADED METHOD AND
OVERLOADED OPERATOR

Definition
1 of overloading function

Create
2 overloading function

Rules
3 of overloading function

4
Definition of operator overloading

5
Rules of operator overloading

6
Create overloaded operator
1 DEFINITION OF OVERLOADED FUNCTION

1. Overloading function is a mechanism; which allows 2 or more


related function to share a same name but the declaration of
parameter functions is different.

2. In this situation, the shared name of a function is called


overload and this process is referred as a function which
shows overloading

3. The function overloading is a method of C++ that applies


polymorphism concept during compiling.

4. The overloading function can reduce the difficulty of a


program by allowing operation to be referred with the same
name.
2 CREATE OVERLOADING FUNCTION

1. Declare all versions of the functions.

2. The compiler automatically with select the most


suitable version of the overloaded function based on
the argument used to call the function.

3. The example shows how the function name set() is


used with 5 different versions:
2 CREATE OVERLOADING FUNCTION (CONT.)

class ABC void main ( )


{ {
int a; ABC object1;
char ab [10]; object1.set(6);
char aks; //pergi ke method 1
float price; object1.set(“SIX”);
public: //pergi ke method 2
void set (int x) //method 1 object1.set (“S”);
{ a=x;} //pergi ke method 3
void set (char xy[10]) //method 2 object1.set (7.5);
{ strcpy(ab,xy); } //pergi ke method 4
void set (char h) //method 3 object1.set (9,8.96);
{ aks=h; } //pergi ke method 5
void set(float p) //method 4 :
{ price =p; } :
void set ( int x, float y )//method 5 };
{ a=x; price = y; }
:
:
};
2 CREATE OVERLOADING FUNCTION (CONT.)
The example below shows how the overloading function f() is overloaded
3 times with different versions.
void f(int i)
{cout<<”In f(int),i is
// Overload fungsi sebanyak 3 kali ”<<i<<’\n’;
#include <iostream> }
using namespace std; void f(int i,int j)
{cout<<”In f(int,int),i is
void f(int i);//parameter berjenis ”<<i;
integer cout<<”,j is”<<j<<’\n';
void f (int i,int j);/* 2 parameter }
berjenis void f (double k)
integer */ {cout<< “In f(double),k is
void f(double k);/*1 parameter “<<k<<’\n’;
berjenis }
double */
Output
int main()
{f(10);//Memanggil f(int)
f(10,20);//Memanggil f(int,int)
f(12.23);//Memanggil f(double)
return 0;
}
3 RULES OF OVERLOADING FUNCTION

1. Different parameter:
The numbers of parameter received for each version must be different.
The type of parameter received must be different.

The return data type can be same or different for overloading function.

2. The example shown has an error because the numbers and types of parameter
are the same.

/* Ini merupakan contoh yang tidak


NOTA
betul dan tidak kompil. */
int f1(int a); Pengkompil tidak tahu f1( ) versi
double f1(int a); yang mana satu perlu dipanggil.
.
.
f1(10); // fungsi yang mana
pengkompil akan panggil?
4 DEFINITION OF OPERATOR OVERLOADING
1. Operator overloading and function overloading is similar.

2. According to the facts, the operator overloading is actually


part of function overloading.

3. When an operator is overload, the original meaning of the


operator is not lost. Besides that, it will have added meaning
to the class, which defines it.

4. Overloaded operator uses overloading function:

•Operator function is a member or a friend to class, which defines it.


•The operator overloading function is different from friend function.
4 DEFINITION OF OPERATOR OVERLOADING (CONT.)

Return
Returnvalue
valueclass-name
class-name::::operator
operator##(list
(listof
ofargument)
argument)
{{
////Operation
Operationtotobe
bedone
done
}}

1. Return value – normally this function returns the type of declared class
(even though the free operator function can return any types of data)

2. The symbol # is placement for the operators that will be overloaded


(example: sign +,++,-,*).

3. The list of argument - depends on how the overloading function is


done.
4 DEFINITION OF OPERATOR OVERLOADING (CONT.)

The example shown below will do the addition operation, deduction and
subtraction on 2 numbers, which are included in user.

#include<iostream.h>
class pilih{
public:
int x;
pilih(){};
pilih(int a)
{x=a;}
pilih operator +(pilih param){
pilih jawapan;
jawapan.x=x+param.x;
return (jawapan);
}
pilih operator -(pilih param){
pilih jawapan;
jawapan.x=x-param.x;
return (jawapan);
}
pilih operator *(pilih param){
pilih jawapan;
jawapan.x=x*param.x;
return (jawapan);}
};
4 DEFINITION OF OPERATOR OVERLOADING (CONT.)

void main()
{
int a,b;
cout<<"Masukkan satu nombor:";
cin>>a;
cout<<"Masukkan nombor kedua:";
cin>>b;
pilih obj1(a);
pilih obj2(b);
pilih obj3,obj4,obj5;
obj3=obj1+obj2;//obj3=obj1.operator +(obj2)
obj4=obj1-obj2;
obj5=obj1*obj2;
cout<<"Hasil Tambah "<<a<<" dan "<<b<<"="<<obj3.x<<"\n";
cout<<"Hasil Tolak "<<a<<" dan "<<b<<"="<<obj4.x<<"\n";
cout<<"Hasil Darab "<<a<<" dan "<<b<<"="<<obj5.x<<"\n";
}
Output
5 RULES IN OVERLOADING OPERATOR

1. Two limitations of operator overloading:


 The precedence of the operator cannot be changed.
 The amount of operand (variables) for the operator cannot be changed even
though the operator function can neglect the operand if the function has an
overload operator /. This means that only one operand can be used.

2. The operator function cannot have default argument.

3. Most of the C++ operators can be overloaded except. :: . * ? and the


pre-process directive. ( .* is special operator).

4. You can use 2 overloading operators: << and >>. This operator is
used in overloading process for I/O.
 These operators are used for I/O processes, but this does not prevent the
operators from doing mathematical function/ task.
6 CREATE OVERLOADED OPERATOR
 Contoh di bawah menunjukkan operator ++ disaratkan terhadap kelas coord.

#include <iostream.h>

class coord {
int x,y;//nilai kordinat
public:
coord() { x=0;y=0;}
coord(int i,int j) {x=i;y=j;}
void get_xy(int &i,int &j) { i=x;j=y;}
coord operator++();
};
//overload ++ untuk kelas coord
coord coord::operator++() Tiada
{x++; parameter
y++;
return *this;}
Output
int main(){
coord o1(10,10);
int x,y;
++o1;//penambahan objek
cout<< “(++o1) X: “<<x<<”,Y:”<<y<< “\n”;
return 0;
}
6 CREATE OVERLOADED OPERATOR (CONT.)
 Contoh program yang mempunyai proses penyaratan unari pengurangan.
#include <iostream.h>
class numbers
{int x,y,z;
public:
void get_data(int,int,int);
void show_data();
void operator-(); // saratkan operator unari
};
void numbers::get_data(int a,int b,int c){
x=a;
y=b;
z=c;
}
void numbers::show_data(){
cout<<”\n x=”<<x;
cout<<”\n y=”<<y;
cout<<”\n z=”<<z;
}
void numbers::operator-() //penakrifan operator –()
{x=-x;
y=-y;
z=-z;
}
6 CREATE OVERLOADED OPERATOR (CONT.)

void main(){ Output


numbers num;//membina object
num.get_data(11,-22,33);
cout<<”\n The numbers are:”;
num.show_data();
-num;//memanggil operator –()
cout<<”\n The numbers are:”;
num.show_data();
cout<<endl;
}
2.6 : WRITE PROGRAM USING TEMPLATE

1 Define Template

2 Declare function templates


1 DEFINE TEMPLATE

1. Template can be assumed as one that can be used to


develop a function or class.

2. C++ use template to achieve polymorphism that is during


compilation.

3. One example of template in real world is a cake mould. A


cake mould can be used for making a chocolate or fruit
cake.

Kek coklat

Boleh digunakan
Acuan kek
untuk membuat

Kek buah
1 DEFINE TEMPLATE

4. By using template, it allows programmer create generic


function and generic class function.

5. Generic function is a draft for a function that can be used to


generate a few same functions in different version.

6. The advantages of a template are that coding can be shortened


and made easier. If using generic class, new classes can built
without coding the definition, only by using the current generic
class.
2 DECLARE FUNCTION TEMPLATES
1. Generic function defines a general set of operations that
can be used on various types of data.
2. Generic function is created using the keyword template,
followed by a formal template parameter list, which is
enclosed within angle bracket (< >). Each parameter
represents data types must be began with class keyword.
After that, function name for generic function will be
defined.
3. Below is a general form for generic function definition.
template
template <class
<class JenisData>
JenisData> nama_Fungsi(
nama_Fungsi( ))
{{
//badan
//badan fungsi
fungsi
}}
2 DECLARE FUNCTION TEMPLATES (CONT.)

template< class segi4>


void luas(segi4 panjang,segi4
lebar){
:
luas (i,j) : luas (y,z)
}

Apabila nilai integer i Apabila nilai double y


dan j dihantar ke fungsi dan z dihantar ke fungsi
generik generik

template <class segi4> template <class segi4>


void luas(segi4 i, segi4 j) void luas(segi4 y, segi4
{ segi4 segi; z)
segi= i * j; { segi4 segi;
cout<<segi<<'\n'; segi= y * z;
} cout<<segi<<'\n';
}
2 DECLARE FUNCTION TEMPLATES (CONT.)
1. You can define more than one generic data type in a template statement
by using coma (,) to separate generic data types.

2. The program given below used to compare 2 values.

#include <iostream.h>

template<class banding1, class banding2>


void perbandingan( banding1 x, banding2 y){
if (x>y)
cout<<" Nilai "<<x<<" lebih besar daripada nilai
"<<y<<'\n';
else
cout<<" Nilai "<<y<<" lebih besar daripada nilai
"<<x<<'\n';
} Output
void main()
{
perbandingan(2,0.11);
perbandingan(0.99,10);
}
2 DECLARE FUNCTION TEMPLATES (CONT.)

template<class banding1,class banding2>


void perbandingan(banding1 x,banding2 y)
{
:
}
perbandingan(2,0.11); perbandingan(0.99,10);

Apabila nilai 2 dan 0.11 Apabila nilai 0.99 dan 10


Apabila
dihantarnilai 2 dan generik
ke fungsi 0.11 dihantar ke dihantar ke fungsi generik
fungsi generik
Memegang Memegang
data integer data double

void perbandingan( banding1 2, void perbandingan( banding1 0.99,


banding2 0.11) banding2 10)
{ {
: Memegang data : Memegang data
: double : integer
} }
2 DECLARE FUNCTION TEMPLATES (CONT.)

1. When you call generic function, argument of function will


determine types of data that will be used in function.

2. However, C++ allows you to do pre-definition data types


by determining types of data that you want program to
manipulate.
2 DECLARE FUNCTION TEMPLATES (CONT.)
The program example below is used to calculate the area of a rectangle
by using specific generic type conditions for integer type data.

#include <iostream.h>

template <class segi4>


void luas(segi4 panjang, segi4 lebar)
{ segi4 segi;
segi= panjang * lebar;
cout<<segi<<'\n';
}
void luas(int panjang, int lebar)
{ int segi;
segi= panjang * lebar;
cout<< "Luas segiempat dalam nilai integer:
"<<segi<<'\n';
}

Explicit overloading generic type for integer


2 DECLARE FUNCTION TEMPLATES (CONT.)

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';
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);
Output
}
2 DECLARE FUNCTION TEMPLATES (CONT.)
template <class segi4>
void luas(segi4
panjang, segi4 lebar){
:
}
luas(i,j) luas(y,z)
Nilai integer i dan j dihantar ke fungsi Nilai integer y dan z dihantar
generik yang mempunyai pra-takrifan ke fungsi generik yang umum
jenis data integer

void luas(int i, int j) void luas(segi4 y, segi4 z)


{ {
: :
} }
2 DECLARE FUNCTION TEMPLATES (CONT.)
1. Generic function is almost like an overloaded function except it has more
limitation.
2. Generic function must do the same action for all version - only data types
can be different.
3. This program shows error when outdata() function do not do the same
thing.

void outdata (int i)


{
cout << i; PENERANGAN
}
Fungsi di atas tidak boleh ditempatkan semula
void outdata(double d) oleh fungsi generik kerana ia tidak membuat
{ perkara yang sama.
cout << d*3.1416;
}
2 DECLARE FUNCTION TEMPLATES (CONT.)
1. When you create generic class, you built class that
defines all algorithm used by class, but the actual data
types that is being manipulated will be specified as
parameter when object for the class is created.

2. Generic class is useful when class uses logical that can


be made as general conclusion.

3. Example: The same algorithm to maintain integer rows will


work for character rows.

4. When you create generic class, it can implement operation


that you defined.

5. Compiler will generate correct object types automatically;


based on types you’ve specified when object is created.
2 DECLARE FUNCTION TEMPLATES (CONT.)
6. Generic class definition begins with the keyword template followed by
parameter list for that template that written in < >. Then followed by
identifier that represents name of that generic class, and followed by
class members that written in {}.

7. Below is a general form for generic class.


template
template <class
<class
JenisData>
JenisData> class
class
Nama_Kelas{
Nama_Kelas{
::
::
}}

8. When you have built generic class, you built specific object for that
class by using a general form as below:
Nama_Kelas
Nama_Kelas <jenisData>
<jenisData>
Nama_Objek;
Nama_Objek;

DataType is data type that will be referred by the class during operation.
2 DECLARE FUNCTION TEMPLATES (CONT.)
 This example shows how calculation for triangle and rectangle is done by
using generic class.
#include <iostream.h> void main()
template<class type1> { int ukur1,ukur2,pilihan;
class Bentuk { char terus;
type1 u1, u2, pilihan, luas; Bentuk<double> segi3;
Bentuk<double> segi4;
public:
Luas(type1 ,type1 ,type1 ); cout<<"Pilih 1 utk mengira luas
}; segiempat\n";
cout<<"Pilih 2 utk mengira luas
template<class type1> segitiga\n";
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’;
}
}
2 DECLARE FUNCTION TEMPLATES (CONT.)
do{ case 2:{
cout<<"Pilihan anda: "; pilihan= 2;
cin>>pilihan; cout<<"nilai tapak: ";
cin>>ukur1;
switch(pilihan){ cout<<"nilai tinggi: ";
case 1: { cin>>ukur2;
pilihan = 1; cout<<"Luas segitiga ";
cout<<"nilai lebar: "; segi3.Luas(2,ukur1,ukur2);
cin>>ukur1; break;
cout<<"nilai tinggi: "; }
cin>>ukur2; }
segi4.Luas(1,ukur1,ukur2); cout<<" Mahu membuat pengiraan lain?
break; (Y/N) \n";
} cin>>terus; }
Output while (terus=='Y'||terus=='y');
}
2 DECLARE FUNCTION TEMPLATES (CONT.)
template<class type1> class Bentuk

Pilihan 1 Pilihan 2
Segi4.luas(1,ukur1,ukur2) Segi3.luas(2,ukur1,ukur2
)

template<class type1> template<class type1>


Bentuk<type1>::Luas(type1 1,type1 Bentuk<type1>::Luas(type1 2,type1
ukur1, ukur1,
type1 ukur2) type1 ukur2)
{ if (pilihan ==1) { :
{ :
luas=ukur1 * ukur2; if (pilihan == 2)
cout<<"luas segiempat: {
"<<luas<<’\n’; luas=ukur1 * ukur2;
} cout<<"luas segitiga:
: "<<luas<<’\n’;
: }
} }
2 DECLARE FUNCTION TEMPLATES (CONT.)
PENERANGAN
Dalam contoh aturcara ini, kelas generik bentuk digunakan untuk membentuk dua objek
iaitu objek segi3 dan objek segi4 melalui pernyataan :
Bentuk<double>segi3;
Bentuk<double>segi4;

Apabila pengguna memilih pilihan satu, segi4.luas(1, ukur1, ukur2) akan menghantar
argumen-argumen 1, ukur1 dan ukur2 ke dalam fungsi luas() yang terdapat dalam kelas
generik bentuk dan memberi nilai 1 pada pembolehubah pilihan, nilai ukur1 pada
pembolehubah u1 dan nilai ukur2 pada pembolehubah u2.

Kemudian nilai-nilai argumen yang telah diberi nilai akan digunakan untuk mengira nilai
luas segiempat.

Hal yang sama akan dilakukan jika pengguna membuat pilihan dua di mana
segi3.luas(2, ukur1.ukur2) akan menghantar argumen-argumennya ke dalam fungsi
luas() yang terdapat pada kelas generik bentuk untuk memberi nilai argumen-argumen
tersebut dengan pembolehubah yang ada pada fungsi luas() dan menggunakan nilai-
nilai yang diberi nilai untuk mengira luas segitiga pula.
2 DECLARE FUNCTION TEMPLATES (CONT.)
1. Generic class can consist more than one generic data type.

2. Declaration of all data types needed by class made by using coma sign (,)
in template determination.

3. Example below shown program to determine total price for theatre tickets .

#include<iostream.h> void main()


#include<stdlib.h> { buku<int,double> a;
#include<string.h> int pilih,unit;
template <class Type1,class Type2> char tambah;
class buku double kira1,kira,harga;
{ Type1 pilih,unit; kira=0,kira1=0;
Type2 harga,kira1,jumlah; cout<<"KAUNTER TIKET TEATER SI
public: CINDAI\n";
Type2 Harga(Type1 a,Type2 b){ cout<<"Masukkan pilihan
unit=a; kategori :\n";
harga=b; cout<<"1.Dewasa\n";
jumlah=harga*unit; cout<<"2.Kanak-kanak\n";
return jumlah; }
};
2 DECLARE FUNCTION TEMPLATES (CONT.)
do {
cout<<"Pilihan anda:";
cin>> pilih;
switch(pilih){
case 1: Output
harga=10.00;
break;

case 2:
harga=5.00;
break;

default:
cout<<"Input salah\n";
break;
}
cout<<"Bilangan tiket:";
cin>>unit;
kira1=kira1 + a.Harga(unit,harga);
cout<<"Mahu teruskan operasi? (Y/N)\n";
cin>>tambah;
}while(tambah=='Y'||tambah=='y');
cout<<"Jumlah Bayaran:RM"<<kira1;
}
2 DECLARE FUNCTION TEMPLATES (CONT.)
#include <iostream.h>
template<class segi4>
class Kira{
segi4 panjang, lebar;
public:
luas (segi4, segi4);
};
template <class segi4>
Kira <segi4>::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;
Kira<double> a;
cout<<"Panjang (dalam nilai integer):
"<<i<<'\n';
cout<<"Lebar (dalam nilai integer): "<<j<<'\n';
cout<<"Luas segiempat dalam nilai integer: ";
a.luas (i,j);
cout<<"Panjang (dalam nilai double):
"<<y<<'\n';
cout<<"Lebar (dalam nilai double): "<<z<<'\n';
cout<<"Luas segiempat dalam nilai double: ";
a.luas (y,z);
}

S-ar putea să vă placă și