Upload
munna-pehlwan
View
223
Download
0
Embed Size (px)
Citation preview
7/29/2019 Intro to Abstract Data Types
1/40
IntroductiontoAbstractDataType&C++
NorBahiahHjAhmad&Dayang
NorhayatiA.
Jawawi
SCJ2013DataStructure&Algorithms
1
7/29/2019 Intro to Abstract Data Types
2/40
ObjectivesAttheendoftheclassstudentsareexpectedto:
UnderstandAbstractDataTypeconcept ReviewC++programming
Declaring
aclass,
data
member
and
function
member
Creatingconstructoranddestructor
Pass objectasfunctionparameter
Returnobjectfromafunction
Arrayof
class
Pointertoclass
2
7/29/2019 Intro to Abstract Data Types
3/40
Abstraction
Abstractdatatype(ADT)
x Acollectionofdataandasetofoperationsonthedata
x Giventheoperationsspecifications,theADTsoperations
canbeusedwithoutknowingtheirimplementationsor
howdata
is
stored,
Abstraction
Thepurposeofamoduleisseparated fromits
implementation Specificationsforeachmodulearewrittenbefore
implementation
3
7/29/2019 Intro to Abstract Data Types
4/40
Abstraction
Dataabstraction
x Focuseson
the
operations of
data
(whatyou
can
do
to
a
collectionofdata),notontheimplementationofthe
operations(howyoudoit)
x
develop
each
data
structure
independently
from
the
rest
ofthesolution
Functionalabstraction
Separatesthepurposeofamodulefromits
implementation
4
7/29/2019 Intro to Abstract Data Types
5/40
InformationHiding
Informationhiding
Hidethe
details
within
amodule.
Tolimitthewaytodealwithmoduleanddata,sothatothermodulecannotmodifythedata.
Makesthese
details
inaccessible
from
outside
the
module.
5
7/29/2019 Intro to Abstract Data Types
6/40
AbstractionExample
6
bookbook
book
title
year
author
publisher
price
getData()
print()
checkPrice()
checkPublisher()
Abstracion of bookAbstracion of book
abstract to attributes
behavior
Abstraction of a book
7/29/2019 Intro to Abstract Data Types
7/40
Encapsulation
Theprocessofcombiningdataandfunctionsintoa
singleunitcalledclass.
Theprogrammercannotdirectlyaccessthedata.
Dataisonlyaccessiblethroughthefunctionspresent
insidetheclass.
Dataencapsulationisanimportantconceptofdata
hiding.
7
7/29/2019 Intro to Abstract Data Types
8/40
C++Classes
Aclassdefinesanewdatatype
Aclass
contains
data
members
and
methods
(memberfunctions)
Bydefault,
all
members
in
aclass
are
private
Butcanbespecifiedaspublic
Anobjectisaninstanceofaclass
8
7/29/2019 Intro to Abstract Data Types
9/40
C++Class
Definition
9
class clasName{
public:list of data member declaration;list of function member declaration;
private:list of data member declaration;list of function member declaration;
}; // end class definition
public :membersthatareaccessiblebyothermodules
private :members
that
are
hidden
from
other
modules
and
canonlybeaccessedbyfunctionmemberofthesameclass.
class memberdeclarations:data memberand
functionmember
7/29/2019 Intro to Abstract Data Types
10/40
ClassDefinition
for
Book
10
classbook
{private:
// data member declaration as private
float price;
int year;
char author[20], title[25];
public:
book(); // Default constructor
// Constructor with parmeter
book(char *bkTitle,double bkPrice);
book(int = 2000);
// C++ function
void getData();void print( );
float checkPrice( )const;
char * getAuthor();
~book() ; // destructor
}; // end book declaration
7/29/2019 Intro to Abstract Data Types
11/40
ClassMethods
Classmethodsconsistsof
Constructor
Destructor
C++functions.
const function
11
7/29/2019 Intro to Abstract Data Types
12/40
Constructors Constructors
Usedto
create
and
initialize
new
instances
of
aclass
Isinvokedwhenaninstanceofaclassisdeclared
Havethesamenameastheclass
Haveno
return
type,
not
even
void
Aclasscanhaveseveralconstructors However,compilerwillgenerateadefaultconstructorifno
constructoris
defined.
12
7/29/2019 Intro to Abstract Data Types
13/40
ConstructorProperties
Morethanoneconstructorcanbedeclared
Eachconstructor
must
be
distinguished
by
the
arguments.book();
book(char *bkTitle,double bkPrice);book(int = 2000);
Defaultconstructor: book();
Canhave
argument:
book(char *bkTitle,double bkPrice);
Canhavedefaultargument:
book(int = 2000); 13
7/29/2019 Intro to Abstract Data Types
14/40
DefaultConstructor
Implementation
Setsdatamemberstoinitialvalues
Instancedeclaration:
book myBook;
InstancemyBook is
created
with
the
price
set
to
10.0,author settoDayang Norhayati,titlesettoLearnDataStructureandyearsetto2012
14
book::book()
{ price = 10.00;
strcpy (author,Dayang Norhayati);
strcpy (title, Learn Data Structure);
year = 2012;} // end default constructor
7/29/2019 Intro to Abstract Data Types
15/40
ConstructorwithArgument
Implementation
15
book::book (char *bkTitle,double bkPrice){ strcpy (title, bkTitle);
price = bkPrice;
}
Instance declaration:book myBook(NorBahiah,25.00);
Price is set to 25.00
Authoris set to NorBahiah
7/29/2019 Intro to Abstract Data Types
16/40
Constructor
With
Default
Argument
Implementation
2 methods oftodeclareinstanceofaclass:
book myBook; // set year to default value, 2000
book yourBook(2009); // set year to 2009
Avoidambiguityerror whenimplementingconstructor
withdefaultargument
book::book(int year);
// Constructor with default argument{ price = 10.00;
strcpy (author,NorBahiah);
strcpy (title, Learn C++);
} // end default constructor
7/29/2019 Intro to Abstract Data Types
17/40
Destructor Destroysaninstanceofanobjectwhenthe
objectslifetime
ends
Eachclasshasonedestructor
Thecompilerwillgenerateadestructorifthe
destructoris
not
defined
Example: ~book();
17
book::~book()
{ cout
7/29/2019 Intro to Abstract Data Types
18/40
FunctionMember
Implementation
Methodto
call
the
member
function:
Frommain() ornonmemberfunction
cout title;
}
float book::checkPrice( )const
{ return price; }
7/29/2019 Intro to Abstract Data Types
19/40
Classesas
Function
Parameters
Classobjectscanbepassedtoanotherfunctionas
parameters 3methodsofpassingclassasparametertofunction
Passbyvalue
Passbyreference
Passbyconstreference
Passbyvalue Anychangethatthefunctionmakestotheobjectisnotreflectedinthecorrespondingactualargument
inthe
calling
function.
19
7/29/2019 Intro to Abstract Data Types
20/40
Passby
value
20
class subject
{
private:
char subjectName[20];
char kod[8];int credit;
public:
subject (char *,char *,int k=3);
void getDetail();
friend void changeSubject(subject);};
subject:: subject (char *sub,char *kd,int kre)
{ strcpy(subjectName,sub);
strcpy(kod,kd);
credit = kre;
}
void subject:: getDetail()
{cout
7/29/2019 Intro to Abstract Data Types
21/40
Passby
value
Continued
21
// friend function implementation that receive object as
parameter
void changeSubject(subject sub); // receive object sub
{ cout > sub.subjectName;
cout > sub.kod;
cout
7/29/2019 Intro to Abstract Data Types
22/40
Passby
reference
Anychangesthatthefunctionmakestothe
object
will
change
the
corresponding
actual
argument inthecallingfunction.
Functionprototypeforfunctionthatreceivea
referenceobject
as
parameter:
use
operator
&
22
functionType functionName(className & classObject)
{
// body of the function
{
7/29/2019 Intro to Abstract Data Types
23/40
Passby
Reference
23
// pass by reference
// friend function that receive object as parameter
void changeSubject(subject &sub); // operator & is used
{ cout > sub. subjectName;
cout > sub.kod;
cout
7/29/2019 Intro to Abstract Data Types
24/40
const Parameter Referenceparametercanbedeclaredas
const ifwe
dont
want
any
changes
being
donetothedatainthefunction.
Functionprototypeforfunctionthatreceivea
referenceobject
as
parameter.
24
functionType functionName(const className & classObject)
{
// body of the function{
7/29/2019 Intro to Abstract Data Types
25/40
const Parameter
25
void changeSubject(const subject &sub);
// operator const and & is used
{ cout > sub. subjectName;
cout > sub.kod;
cout
7/29/2019 Intro to Abstract Data Types
26/40
Classas
Return
Value
from
Function
Syntaxfordeclaringfunctionthatreturnaclassobject
Syntaxto
call
function
that
return
aclass
objectName = functionName();
where,
objectName,anobjectfromthesameclasswiththetypeofclassreturnfromthefunction. Thisobjectwillbeassignedwiththe
value
returned
from
function
functionName():functionthatreturnclass
26
className functionName(parameter list)
{// function body
}
7/29/2019 Intro to Abstract Data Types
27/40
Classas
Return
Value
from
Function
27
Point findMiddlePoint(Point T1, Point T2)
{
double midX, midY;
midX = (T1.get_x() + T2.get_x()) / 2;
midY = (T1.get_y() + T2.get_y()) / 2;
Point middlePoint(midX, midY);
return middlePoint;}
Point point1(10,5), point2(-5,5);
Point point3; // use defult argumen// point3 is the point in the middle of point1 and point2
point3 = findMiddlePoint(point1,point2)
Function that return a class object, Point
Statement that call function that return a class
Returntype isaclass
CreateinstanceofPoint
Returninstance
of
Point
CallfindMiddlePoint that
returnobjectandassigntopoint3
7/29/2019 Intro to Abstract Data Types
28/40
Arrayof
class
Agroupofobjectsfromthesameclasscanbedeclaredasarrayofaclass
Example: ArrayofclassstudentsregisteredinDataStructure
class
Arrayof
class
lecturer
teaching
at
FSKSM
ArrayofclasssubjectsofferedinSemesterI.
Everyelementinthearrayofclasshasitsown
data
member
and
function
member.
Syntaxtodeclarearrayofobjects:className arrayName[arraySize];
28
7/29/2019 Intro to Abstract Data Types
29/40
29
class staff {
char name[20];
int age ;
float salary;
public:
void read_data() ;
{ cin >> name >> age >> salary;
void print_data()
{ cout
7/29/2019 Intro to Abstract Data Types
30/40
Arrayof
class
2methodstocallmemberfunctionformanager array.
1. Byusingarraysubscriptinordertoaccessmanagerincertain
location
of
the
array.
30
cin >> n ;
manager[n].read_data() ;
cout
7/29/2019 Intro to Abstract Data Types
31/40
PassArray
of
Object
to
Function
class info
{
private:char medicine[15];
char disease[15];
public:
void setMed() { cin >> medicine;}
void setDisease() { cin >> disease;}char*getMedicine(){return medicine;}
char* getDisease() {return disease;}
};
31
Declaration of class info that store information about the disease and therelevant medicine
7/29/2019 Intro to Abstract Data Types
32/40
FunctioncheckMedicine(data) receivesanarrayofobject
info.
Thisfunction
requires
the
user
to
enter
the
name
of
the
diseaseandthefunctionwillsearchforthemedicinethatis
suitableforthedisease.
32
PassArray
of
Object
to
Function
main()
{ info data[10];
for (int n = 0; n < 5; n++)
{ data[n].setMedicine);
data[n].setDisease();}
cout
7/29/2019 Intro to Abstract Data Types
33/40
33
void checkMedicine(info x[])
{ char diseas[20];int found = 0;
cout > diseas;
for (int n = 0; n < 5; n ++)
if (strcmp(diseas, x[n].getDisease()) == 0 )
{ cout
7/29/2019 Intro to Abstract Data Types
34/40
Pointerto
Object
Pointer storeaddressofavariable.
Pointer
can
also
store
address
of
an
object.
Examplestudent student1; // create instance of
student
student* studentPtr = &student1;
CreateapointervariablestudentPtr and
initialize
the
pointer
with
the
address
of
instance
student1
34
7/29/2019 Intro to Abstract Data Types
35/40
Pointerto
Object
2methodstoaccessclassmemberthrough
pointervariable
studentPtr :
1. (*studentPtr).print()
or
2. studentPtr ->print()
35
7/29/2019 Intro to Abstract Data Types
36/40
Pointerto
Object
36
// pointer to object
#include
#include class student
{
private:
char name[30];
unsigned long metricNo;
public: // constructor
student(char* nama,unsigned long num)
{
no_metrik = num;
strcpy(name, nama);
}
void print()
{ cout
7/29/2019 Intro to Abstract Data Types
37/40
Pointerto
Object
ProgramOutput
37
Address of the objectAddress student1: :0x0012ff68Address student2: :0x0012ff44Pointer value
Pointer value for student1:0x0012ff68Pointer value for student2:0x0012ff44Students name: Abdullah
Students metric number: 234234
7/29/2019 Intro to Abstract Data Types
38/40
Pointerto
Object
Operatornew canalsobeusedtoallocatememoryforapointervariable.
Operatordelete destroys
memory
for
apointer
variable.
38
void main()
{
student *ptr = new student("Ahmad", 123123);
ptr -> print();
delete(ptr);
ptr = new student("Abdullah", 234234);
ptr ->print();
delete(ptr);
}
7/29/2019 Intro to Abstract Data Types
39/40
Conclusion
and
Summary AbstractDataTypeisacollectionofdataandasetofoperationson
thedata.
Abstractionimplements
information
hiding
and
encapsulation,
wherebyothermodulescannottamperwiththedata.
InC++,abstractionisimplementedbyusingclass. Inclassdeclaration,therearedeclarationofdatamembersand
functionmembers
Functionmembersconsistsofconstructor,destructor,c++functionandconst function.
Objectcanbepassedasfunctionparameterbyvalueorbyreference.
Returntype
of
afunction
can
also
be
aclass.
AnArrayandPointercanalsobedeclaredoftypeclass.
39
7/29/2019 Intro to Abstract Data Types
40/40
References
1. NorBahiah etal.Struktur data&algoritmamenggunakan C++.Penerbit UTM,2005
2. Richrd F.Gilberg andBehrouz A.Forouzan,
DataStructuresAPseudocode ApproachWithC++,Brooks/ColeThomsonLearning,2001.
12/3/2011 40