Upload
f3031
View
241
Download
0
Embed Size (px)
Citation preview
8/9/2019 OOP Chapter2
1/73
8/9/2019 OOP Chapter2
2/73
Understand the concept of Classes and Objects
Use Constructor in Program
Use Destructor in Program
Create classes and function as a friend
Create overloaded method and overloaded operator
Write program using Templates
2.1
2.2
2.3
2.4
2.5
2.6
8/9/2019 OOP Chapter2
3/73
Define Class
Define Method
Access Specifier
Declare Objects
1
2
3
4
8/9/2019 OOP Chapter2
4/73
1
General format for defining a class :
class ClassName{
// Data definition
// Method definition};
**TIPS**
*Keywordclass is a must in defining a class.
* Semicolon (;) must be placed after closing braces each time
you define a class.
8/9/2019 OOP Chapter2
5/73
1
class Rectangle
{ int length, width;
public :
void set_data (int x,int y)
{ length=x;
width=y;
}
double calculate_area()
{ return length*width;}
};
Method definition
ClassName
Data member definition
Keyword for defining a class
Access
control
8/9/2019 OOP Chapter2
6/73
2
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;}};
8/9/2019 OOP Chapter2
7/73
2
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);
};
void Student::set_data(int a,int b,char * c,double d){
ID=a;age=b;strcpy(name,c);
mark=d;}
declare
define
8/9/2019 OOP Chapter2
8/73
3
Three type of access specifier for data members and
methods:
1. Public
2. Private3. Protected
8/9/2019 OOP Chapter2
9/73
3
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 ( );
};
8/9/2019 OOP Chapter2
10/73
3
2.Private Private members can only be achieved by functional members
and friends for a class, whichhas 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;
int value2;int func2 (char*);void func1 (long);
};
Private Data
Private Method
8/9/2019 OOP Chapter2
11/73
3
1. Protected
Protected members are accessible in
the class where it is declared and also
any other classes, which are inherited
from that class. Definition of friend does not give any
effect to this access control.
Example of the use of this keyword in
the real world:
Total savings for a student.
Only certain people knows the actualtotal savings by a student
such as his/her family members.
class A{ protected:
int valueA;};class B : public A
{ public:void FuncB( );
};class C : public B{
public:void FuncC( );
};
8/9/2019 OOP Chapter2
12/73
4
Syntax:
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
className objectName;
8/9/2019 OOP Chapter2
13/73
4
8/9/2019 OOP Chapter2
14/73
Define Constructor
Characteristics of Constructor
Types of Constructors
(Use Constructors in Program)
1
2
3
8/9/2019 OOP Chapter2
15/73
1
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.
8/9/2019 OOP Chapter2
16/73
2
Constructorhas the same name as the class.
For example constructor for class Employee is declared as:
class Employee{public:
Employee ( ); /* pengisytiharanconstructor */};
Nama kelas
Nama method
constructor
The constructors 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 dont have to invoke it like other
functions.
8/9/2019 OOP Chapter2
17/73
3
1.Default Constructor
2.Parameterized Constructor
3.Initialization Constructor
4.Copy Constructor
5.Overloading Constructor
8/9/2019 OOP Chapter2
18/73
3
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.
Secara automatik,
pengisytiharan objek ini akan
menyebabkan aturcara
memperuntukkan ruang
memori untuk objek box1.Untuk mewujudkan beberapa
objek, kelas harus mempunyai
constructorlalai.
NOTA
#include
class box {private:
float length, width;public:box ( ); // defaultconstructorvoid input( );
void area ( );};void main(){
boxbox1; // pengistiharan kelas}
Method constructortidak menerima sebarang nilai
8/9/2019 OOP Chapter2
19/73
3
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.
#includeclass SegiEmpat{int panjang,lebar;
public:SegiEmpat(int a, int b):panjang(a),lebar(b){}int kira_luas(){return panjang * lebar;}
};void main(){int m,n;coutm;coutn;SegiEmpat S(m,n);cout
8/9/2019 OOP Chapter2
20/73
3
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){}};
y Data panjang akan diberikan nilai 10 manakala nilai data lebar akan diberikan
nilai 20.
y { } masih diperlukan.
8/9/2019 OOP Chapter2
21/73
The example of a program is to calculate the area of a rectangle based
on the value given on method constructor.
#includeclass SegiEmpat{
int panjang,lebar;public:SegiEmpat():panjang(10),lebar(20){}
int kira_luas(){return panjang * lebar;
}};void main(){SegiEmpat a;cout
8/9/2019 OOP Chapter2
22/73
3
4.Copy Constructor
1. Changing the private data value through a constructor.
SegiEmpat a (1,2);SegiEmpat b(a);
Objek b akan menyalin nilai yang
dimiliki oleh objek a
#include
class SegiEmpat{int panjang,lebar;public:SegiEmpat(int a, int b):panjang(a),lebar(b){}int kira_luas(){return panjang * lebar;}};
void main(){int m,n;coutm;coutn;SegiEmpat S(m,n);SegiEmpat Z(S);cout
8/9/2019 OOP Chapter2
23/73
3
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 begiven initial value but not foro2.
8/9/2019 OOP Chapter2
24/73
3
5.Overloading Constructor
#includeclass SegiEmpat_Sama{
int panjang ;public:SegiEmpat_Sama ( ) { panjang = 5; }SegiEmpat_Sama ( int n ) { panjang=n;}int luas(){return panjang*panjang;}};int main(){
SegiEmpat_Sama o1(10); /* isytiharkanobjek dengan nilai awalan */
SegiEmpat_Sama o2; /* isytiharkantanpa nilai Awalan */
cout
8/9/2019 OOP Chapter2
25/73
Define Destructors
Types of Destructors
Use Destructors in Program
1
2
3
8/9/2019 OOP Chapter2
26/73
1
1. The destructor is a function that is called automaticallywhen an object is destroyed or goes out of scope.
2. The destructor reclaims the memory that is allocated to
the object.
8/9/2019 OOP Chapter2
27/73
2
1. A destructorhas 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 adestructor.
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 dont have to invoke it like
other functions.
8/9/2019 OOP Chapter2
28/73
3
#includeclass SegiEmpat{int panjang,lebar;public:SegiEmpat();
~SegiEmpat();
int kira_luas(){return panjang * lebar;}
};void main(){SegiEmpat a;cout
8/9/2019 OOP Chapter2
29/73
Define friend
Declare a friend
Declaring function as a friend
Declaring class as a friend
1
2
4
3
8/9/2019 OOP Chapter2
30/73
1
1. A function or class can be defined as a friend to otherclasses
2. If a function or class becomes the friend to another
class, for example class or function Abecomes the
friend to class C, class or function A can access privatemember 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.
8/9/2019 OOP Chapter2
31/73
2
1. The declaration for friend can be done throughnumerous 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 inthe Maths class.
8/9/2019 OOP Chapter2
32/73
3
1. By placing th
e keyword friend in front of th
e functions name, th
e functioncan 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.
8/9/2019 OOP Chapter2
33/73
3
The example below shows how the calculation of area for the
rectangle is made using friend.
Ahli kelas SegiEmpat yang
disimpan ditempat yang sulit(data-data private)
Kelas SegiEmpatFungsi
Kira_Luas
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.
8/9/2019 OOP Chapter2
34/73
#include
class SegiEmpat{int panjang,lebar;
public:SegiEmpat(int a,int b){panjang=a;lebar=b;}friend int Kira_Luas(SegiEmpat x);};int Kira_Luas(SegiEmpat x){return x.panjang * x.lebar; }
void main(){int a, b;
couta;coutb;SegiEmpat tepat(a,b);cout
8/9/2019 OOP Chapter2
35/73
4
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{friend class segiempat;..
public:..};class segiempat
{private:.
public:};
Shape class
declared class
Square as a friend
to class Shape. This
means the class
Square can achieve
private member forclass Shape.
.
8/9/2019 OOP Chapter2
36/73
4
Below is an example which shows class markah_pelajar becomes
friend to class info_pelajar to enable data memberinfo_pelajaraccess data member from class markah_pelajar.
#include #include
class markah_pelajar;
class info_pelajar {friend class markah_pelajar;
private:char nama[30],ic[10];
public:void setdata(char *,char *);
};void info_pelajar::setdata(char *a,char *b){ strcpy(nama,a);
strcpy(ic,b);}
class markah_pelajar{float markah1,markah2,jumlah;
public:void setmarkah(float,float);
void kiraMarkah();void paparan(info_pelajar);
};
voidmarkah_pelajar::setmarkah(floatujian1,
float ujian2){ markah1=ujian1;
markah2=ujian2;}
8/9/2019 OOP Chapter2
37/73
4
void markah_pelajar::kiraMarkah()
{jumlah=markah1 + markah2;}void
markah_pelajar::paparan(info_pelajara){cout
8/9/2019 OOP Chapter2
38/73
4
Output
8/9/2019 OOP Chapter2
39/73
Definition of overloading function
Create overloading function
Rules of overloading function
Definition of operator overloading
Rules of operator overloading
Create overloaded operator
1
2
3
4
6
5
8/9/2019 OOP Chapter2
40/73
1
1. Overloading function is a mechanism; which allows 2 ormore related function to share a same name but thedeclaration 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 whichshows overloading
3. The function overloading is a method of C++ that appliespolymorphism concept during compiling.
4. The overloading function can reduce the difficulty of aprogram by allowing operation to be referred with thesame name.
8/9/2019 OOP Chapter2
41/73
2
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 with5 different versions:
8/9/2019 OOP Chapter2
42/73
2
class ABC
{int a;char ab [10];char aks;float price;
public:void set (int x) //method 1{ a=x;}void set (char xy[10]) //method 2{ strcpy(ab,xy); }void set (char h) //method 3{ aks=h; }void set(float p) //method 4{ price =p; }void set ( int x, float y )//method 5{ a=x; price = y; }
::};
void main ( )
{ABC object1;object1.set(6);//pergi ke method 1object1.set(SIX);//pergi ke method 2object1.set (S);//pergi ke method 3object1.set (7.5);//pergi ke method 4object1.set (9,8.96);//pergi ke method 5::};
8/9/2019 OOP Chapter2
43/73
2
The example below shows how the overloading function f() is overloaded
3 times with
different versions.
// Overload fungsi sebanyak 3kali
#include using namespace std;
void f(int i);//parameterberjenis
integervoid f (int i,int j);/* 2 parameter
berjenis
integer */
void f(double k);/*1 parameterberjenis
double */
int main(){f(10);//Memanggil f(int)f(10,20);//Memanggil f(int,int)f(12.23);//Memanggil f(double)return 0;}
Output
void f(int i){cout
8/9/2019 OOP Chapter2
44/73
3
1. Different parameter:
The numbers of parameter received for each version must be different.
The type of parameter received must be different.
2. The example shown has an errorbecause the numbers and types of
parameter are the same.
The return data type can be same or different for overloading function.
/* Ini merupakan contohyangtidak
betul dan tidak kompil. */
int f1(int a);double f1(int a);..f1(10); // fungsiyangmana
pengkompil akan panggil?
Pengkompil tidak tahu f1( ) versi
yang mana satu perlu dipanggil.
NOTA
8/9/2019 OOP Chapter2
45/73
4
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 theoperator is not lost.Besides that, it will have added meaning
to the class, which defines it.
4. Overloaded operatoruses overloading function:
Operator function is a member or a friend to class, which defines it.
The operator overloading function is different from friend function.
8/9/2019 OOP Chapter2
46/73
4
1. Return value normally this function returns the type ofdeclared class (even though the free operator function canreturn any types of data)
2. The symbol # is placement for the operators that will beoverloaded (example: sign +,++,-,*).
3. The list of argument - depends on how the overloadingfunction is done.
Return value class-name :: operator # (list of argument)
{
// Operation to be done
}
8/9/2019 OOP Chapter2
47/73
4
The example shown below will do the addition operation, deduction and
subtraction on 2 numbers, which are included in user.
#includeclass 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);}
};
8/9/2019 OOP Chapter2
48/73
4
void main()
{int a,b;couta;coutb;pilih obj1(a);pilih obj2(b);
pilih obj3,obj4,obj5;obj3=obj1+obj2;//obj3=obj1.operator +(obj2)obj4=obj1-obj2;obj5=obj1*obj2;cout
8/9/2019 OOP Chapter2
49/73
5
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: >.This operator is
used in overloading process forI/O.
These operators are used forI/O processes, but this does not prevent the
operators from doing mathematical function/ task.
8/9/2019 OOP Chapter2
50/73
6
Contoh di bawah menunjukkan operator ++ disaratkan terhadap kelas coord.
#include
class coord {int x,y;//nilai kordinatpublic: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++(){x++;y++;return *this;}
int main(){coord o1(10,10);int x,y;++o1;//penambahan objekcout
8/9/2019 OOP Chapter2
51/73
6
Contoh program yang mempunyai proses penyaratan unari pengurangan.
#include 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
8/9/2019 OOP Chapter2
52/73
6
void main(){
numbers num;//membina object
num.get_data(11,-22,33);
cout
8/9/2019 OOP Chapter2
53/73
Define Template
Declare function templates
1
2
8/9/2019 OOP Chapter2
54/73
1
1.Template can be assumed as one t
hat can be used todevelop 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.
Boleh digunakan
untuk membuat
Kek coklat
Kek buah
Acuan kek
8/9/2019 OOP Chapter2
55/73
1
4. By using template, it allows programmer create genericfunction 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.
8/9/2019 OOP Chapter2
56/73
8/9/2019 OOP Chapter2
57/73
8/9/2019 OOP Chapter2
58/73
2
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
templatevoid perbandingan( banding1 x, banding2 y){
if (x>y)cout
8/9/2019 OOP Chapter2
59/73
8/9/2019 OOP Chapter2
60/73
2
1. Wh
en you call generic function, argument of function willdetermine 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.
8/9/2019 OOP Chapter2
61/73
#include
template void luas(segi4 panjang, segi4 lebar){ segi4 segi;
segi= panjang * lebar;cout
8/9/2019 OOP Chapter2
62/73
2
void main(){
int i=10,j=20;
double y=10.1,z=4.2;
cout
8/9/2019 OOP Chapter2
63/73
2
template void luas(segi4
panjang, segi4 lebar){:}
luas(i,j) luas(y,z)
Nilai integer i dan j dihantar ke fungsi
generik yang mempunyai pra-takrifan
jenis data integer
Nilai integer y dan z dih
antarke fungsi generik yang umum
void luas(int i, int j){
:}
void luas(segi4 y, segi4 z){
:}
8/9/2019 OOP Chapter2
64/73
2
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
8/9/2019 OOP Chapter2
65/73
2
1. When you create generic class, youbuilt 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 youve specified when object is created.
8/9/2019 OOP Chapter2
66/73
2
6. Generic class definition begins with the keyword template followed by
parameter list for that template that written in < >. Then followed byidentifier 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 class
Nama_Kelas{::}
8. When youhave built generic class, youbuilt specific object for that
class by using a general form as below:Nama_Kelas
Nama_Objek;
DataType is data type that will be referred by the class during operation.
8/9/2019 OOP Chapter2
67/73
8/9/2019 OOP Chapter2
68/73
2
do{coutpilihan;
switch(pilihan){case 1: {
pilihan = 1;coutukur1;coutukur2;segi4.Luas(1,ukur1,ukur2);
break;}
case 2:{pilihan= 2;coutukur1;coutukur2;cout
8/9/2019 OOP Chapter2
69/73
2
Pilihan 1Segi4.luas(1,ukur1,ukur2)
Pilihan 2Segi3.luas(2,ukur1,ukur2
)
templateBentuk::Luas(type1 1,type1ukur1,
type1 ukur2){ if (pilihan ==1){
luas=ukur1 * ukur2;cout
8/9/2019 OOP Chapter2
70/73
2
PENERANGAN
Dalam contoh aturcara ini, kelas generik bentuk digunakan untuk membentuk dua objek
iaitu objek segi3 dan objek segi4 melalui pernyataan :
Bentuksegi3;
Bentuksegi4;
Apabila pengguna memilih pilihan satu, segi4.luas(1, ukur1, ukur2) akan menghantar
argumen-argumen 1, ukur1 dan ukur2 ke dalam fungsi luas() yang terdapat dalamkelas 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 manasegi3.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.
8/9/2019 OOP Chapter2
71/73
8/9/2019 OOP Chapter2
72/73
2
do {
cout pilih;switch(pilih){case 1:harga=10.00;break;
case 2:
harga=5.00;break;
default:cout
8/9/2019 OOP Chapter2
73/73
2
#include templateclass Kira{
segi4 panjang, lebar;public:luas (segi4, segi4);
};template Kira ::luas(segi4 panjang, segi4 lebar){ segi4 segi;
segi= panjang * lebar;cout