Documente Academic
Documente Profesional
Documente Cultură
CHAPTER 2
By:
PN. NOR ANISAH BINTI MOHD SAAD
CHAPTER 2.0 : CLASSES AND OBJECTS
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
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 :
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
1. Public
2. Private
3. Protected
3 ACCESS SPECIFIER
1. Public
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.
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
Employee ( ); /* pengisytiharan
constructor */ Nama method
}; 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
#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
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 Define Destructors
2 Types of Destructors
#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
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);
//….
}
The example below shows how the calculation of area for the
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.
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. 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.
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)
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
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.)
1 Define Template
Kek coklat
Boleh digunakan
Acuan kek
untuk membuat
Kek buah
1 DEFINE TEMPLATE
#include <iostream.h>
#include <iostream.h>
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
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
)
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 .
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);
}