Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is...

50
Introduction to Abstract Data Type & & C++ Revision Prepared by N B hi h Hj Ah d Nor Bahiah Hj Ahmad Software Engineering Department, Faculty of Computer Science and Information System

Transcript of Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is...

Page 1: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

Introduction to Abstract Data Type&&

C++ Revision

Prepared by N B hi h Hj Ah dNor Bahiah Hj Ahmad

Software Engineering Department, Faculty of Computer Science and

Information System

Page 2: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

2

ObjectivesjAt the end of the class students are expected to:

• Understand Abstract Data Type concept• Review C++ progrmming▫ Declaring a class, data member and function memberDeclaring a class, data member and function member▫ Creating constructor and destructor▫ Create object as function parameter▫ Return object from a functionReturn object from a function▫ Array of class▫ Pointer to class▫ Define and implement a class within header files and Define and implement a class within header files and

implementation files

Page 3: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

3

Abstraction and Information Hidingg

• Abstraction▫ Separates the purpose of a module from its ▫ Separates the purpose of a module from its

implementation▫ Specifications for each module are written before p b

implementation▫ Functional abstraction

Separates the purpose of a module from its implementation

Page 4: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

4

Abstraction and Information Hidingg▫ Data abstraction

Focuses on the operations of data, not on the i l t ti f th tiimplementation of the operationsAsks you to think what you can do to a collection of data independently of how you do itAllows you to develop each data structure in relative Allows you to develop each data structure in relative isolation from the rest of the solutionA natural extension of functional abstraction

▫ Abstract data type (ADT)yp ( )A collection of data and a set of operations on the dataYou can use an ADT’s operations without knowing their implementations or how data is stored, if you know the

ti ’ ifi tioperations’ specifications

Page 5: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

5

Abstraction and Information Hidingg• Information hiding▫ Hide details within a moduleHide details within a module▫ Ensure that no other module can tamper with

these hidden detailsM k h d il i ibl f id h ▫ Makes these details inaccessible from outside the module

▫ Public view of a moduleub c v ew o a odu eDescribed by its specifications

▫ Private view of a moduleI l t ti d t il th t th ifi ti Implementation details that the specifications should not describe

Page 6: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

6

Abstract data type (ADT)• Abstract data type (ADT)▫ An ADT is composed ofAn ADT is composed of

A collection of dataA set of operations on that data

S ifi i f ADT i di▫ Specifications of an ADT indicateWhat the ADT operations do, not how to implement them

▫ Implementation of an ADTIncludes choosing a particular data structure

Page 7: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

7bookbookAbstracion of book Abstracion of book

Abstraction of a book

booktitle

b yearauthorpublisherprice

abstract to attributes

getData()print()checkPrice()h kP bli h ()

behaviorcheckPublisher()

Page 8: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

8

C++ Classes

• Encapsulation combines an ADT’s data with its operations to form an object operations to form an object ▫ An object is an instance of a class▫ A class defines a new data typeA class defines a new data type▫ A class contains data members and methods

(member functions)▫ By default, all members in a class are private

But you can specify them as publicE l ti hid i l t ti d t il▫ Encapsulation hides implementation details

Page 9: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

9

C++ Classes

An object’s data and methods aremethods are encapsulated

Page 10: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

10

Class definitionclass clasName{public:

list of data member declaration;class members:list of data member declaration;

list of function member declaration;private:

list of data member declaration; list of function member declaration;

data and function

list of function member declaration;}; // end class definition

public : members that are accessible by other modulesprivate : members that are hidden from other modules and can only be accessed by function member of the same y yclass.

Page 11: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

11

Class definitionclass Sphere{public:Sphere(); // Default constructorSphere(); // Default constructorSphere(double initialRadius); // Constructorvoid setRadius(double newRadius);double getRadius()const; //can’t change data membersdouble getDiameter() const;double getDiameter() const;double getCircumference() const;double getArea() const;double getVolume() const;void displayStatistics() const;void displayStatistics() const;~Sphere()

private:double theRadius; // data members should be private}; // end Sphere}; // end Sphere

Page 12: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

12

Class methods/member functions

• Constructor – allocates memory for an object and can initialize new instances of a class to and can initialize new instances of a class to particular values.

• Destructor – destroys an instance of a class Destructor destroys an instance of a class when the object’s lifetime ends.

• C++ function• const function – function that cannot alter data

member of the class

Page 13: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

13

C++ Classes: Constructors

• Constructors▫ Create and initialize new instances of a class▫ Create and initialize new instances of a class▫ Invoked when you declare an instance of the class

▫ Have the same name as the class▫ Have no return type, not even void

• A class can have several constructorsA d f l h ▫ A default constructor has no arguments

▫ The compiler will generate a default constructor if you do not define any constructorsy

Page 14: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

14

Constructor Propertiesp• Can have more than one constructor

(overloading) whereby each constructor must be (overloading) whereby each constructor must be distinguished by the arguments.Sphere(); Sphere(double initialRadius);

• Default constructor: Sphere(); C h t • Can have argument: Sphere(double initialRadius);

• Can have default argument:• Can have default argument:Sphere(double initialRadius =10.00)

Page 15: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

15

Constructor Implementation :default constructordefault constructor

• The implementation of a method qualifies its p qname with the scope resolution operator ::• Sets data members to initial values

Sphere::Sphere() : theRadius(1.0){} // end default constructor

Instance declaration: Sphere unitSphere; // theRadius is set to 1.0

Page 16: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

16

Constructor implementation :Constructor with argumentConstructor with argument

Sphere::Sphere(double initialRadius){

if (initialRadius > 0)theRadius = initialRadius;theRadius initialRadius;

elsetheRadius = 1.0;

} // end constructor} // end constructor

Instance declaration:Instance declaration:Sphere mySphere(5.1);

// set theRadius to 5.1

Page 17: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

17

Constructor implementation:Constructor with default argumentConstructor with default argument

Sphere::Sphere(double initialRadius = 5.00){

if (initialRadius > 0)theRadius = initialRadius;

elsetheRadius = 1.0;

2 methods of to declare instance of a class:

;} // end constructor with default argumen.

2 methods of to declare instance of a class:Sphere mySphere(10.1);// set theRadius to 10.1Sphere mySphere;// set theRadius to default value 5.0Sphere mySphere;// set theRadius to default value 5.0

Must avoid ambiguity error

Page 18: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

18

C++ Classes: Destructors

• Destructor▫ Destroys an instance of an object when the object’s ▫ Destroys an instance of an object when the object s

lifetime ends• Each class has one destructorEach class has one destructor▫ For many classes, you can omit the destructor▫ The compiler will generate a destructor if you do

not define one• Example:

S h ()~Sphere();

Page 19: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

19

Member function Implementation pdouble Sphere::getDiameter() const{ return 2.0 * theRadius; } // end getDiameter

Method to call the member function:• From main() or nonmember function

// end getDiameter

cout << mySphere.getDiameter() << endl;

• From member function

void Sphere::displayStatistics() const{

cout << “\nDiameter = " << getDiameter() << “\nVolume = “ << getVolume() << endl;<< \nVolume = << getVolume() << endl;

} // end displayStatistics

Page 20: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

20

Classes as Function Parameters• Class objects can be passed to another function as

parametersp• 3 methods of passing class as parameter to function ▫ Pass by value

Pass b reference▫ Pass by reference▫ Pass by const reference

• Pass by value – Any change that the function makes to the object is not reflected in the corresponding actual argument in the calling function.

Page 21: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

21

Pass by value : Exampleclass subject{private:

char subjectName[20];char kod[8];int credit;

Have to use friend function to pass object as parameter int credit;

public:subject (char *,char *,int k=3);void getDetail();friend void changeSubject(subject);

object as parameter. This nonmember function is accessing private data member.

};subject:: subject (char *sub,char *kd,int kre){ strcpy(subjectName,sub);

strcpy(kod,kd);credit = kre;credit kre;

}void subject:: getDetail(){cout << "\n\nSubject Name : " << subjectName;

t << "\ S bj t C d " << k dcout << "\nSubject Code : " << kod;cout << "\nCredit hours : " << credit;}

Page 22: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

22

Pass by value : Exampley p// friend function implementation that receive object as parametervoid changeSubject(subject sub); // receive object sub{ cout << "\nInsert new subject name: "; Access class cin >> sub. subjectName;cout << "\nInsert new subject code: ";cin >> sub.kod;cout << "\n Get new information for the subject.";sub. getDetail();

member, including private data

b f sub. getDetail();}main(){ subject DS("Data Structure C++","SCJ2013");DS.getDetail();

( ) //

member from sub.

changeSubject(DS); // pass object DS by valuecout << "\n View the subject information again: ";DS.getDetail(); // the initial value does not changegetch();

};};

Page 23: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

23

Pass by referencey

• Any changes that the function makes to the object will change the corresponding actual object will change the corresponding actual argument in the calling function.

• Function prototype for function that receive a Function prototype for function that receive a reference object as parameter: use operator &

functionType functionName(className & classObject)functionType functionName(className & classObject){

// body of the function}

Page 24: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

24

Pass by reference - Exampley p// pass by reference// friend function that receive object as parametervoid changeSubject(subject &sub); // operator & is used{ cout << "\nInsert new subject name: ";cin >> sub. subjectName;cout << "\nInsert new subject code: ";cin >> sub.kod;cout << "\n Get new information for the subject.";sub. getDetail();

}main(){ subject DS("Data Structure C++","SCJ2013");DS.getDetail();changeSubject(DS); // pass by referencecout << "\n View the subject information again: ";DS.getDetail(); // the value within the object has changedgetch();

};

Page 25: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

25

const parameterp

• Reference parameter can be declared as const if we don’t want any changes being done to the we don t want any changes being done to the data in the function.

• Function prototype for function that receive a Function prototype for function that receive a reference object as parameter.

functionType functionName(const className & classObject){

// body of the function}}

Page 26: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

26

const parameter : Examplep p

void changeSubject(const subject &sub); // operator const and & is used// operator const and & is used{ cout << "\nInsert new subject name: ";cin >> sub. subjectName;cout << "\nInsert new subject code: ";cin >> sub.kod;cout << "\n Get new information for the subject.";sub. getDetail();

}}

In this case, data member for sub is trying to be changed.Error will occur since parameter const cannot be modified.

Page 27: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

27

Class as return value from function

• Syntax for declaring function that return a class object

className functionName(parameter list){

// function body}

• Syntax to call function that return a classobjectName = functionName();hwhere,

▫ objectName, an object from the same class with the type of class return from the function. This object will be assigned with the value returned from function be assigned with the value returned from function

▫ functionName(): function that return class

Page 28: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

Class as ret rn al e from f nction :7/6/[email protected]

28

Class as return value from function : Example

Point findMiddlePoint(Point T1, Point T2){

double midX midY;

Function that return a class object, Point Function type is a class

double midX, midY;midX = (T1.get_x() + T2.get_x()) / 2;midY = (T1.get_y() + T2.get_y()) / 2;Point middlePoint(t midX, midY);return middlePoint;

Create instance of Pointreturn middlePoint;

}

Statement that call function that return a class

Return instance of Point

Point point1(10,5), point2(-5,5);Point point3; // use defult argumenpoint3 = findMiddlePoint(point1, point2)

Statement that call function that return a classCall function that return object, value returned is assigned to point3

point3 findMiddlePoint(point1, point2)// point3 is the point in the middle of point1 and point2

Page 29: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

29

Array of class y• A group of objects from the same class can be

declared as array of a classy• Example:▫ Array of class students registered in Data Structure

class class ▫ Array of class lecturer teaching at FSKSM▫ Array of class subjects offered in Semester I.

• Every element in the array of class has it’s own data member and function member.

• Syntax to declare array of objects : Syntax to declare array of objects : className arrayName[arraySize];

Page 30: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

30

Array of class : Exampley pclass staff {

char name[20]; int age ;int age ; float salary;

public: void read_data() ; { cin >> name >> age >> salary;{ cin >> name >> age >> salary; void print_data() { cout << name << age << salary; }

} ;

main(){

staff manager[20];// declare array of staff

Declare 20 managers from class staff. Each element has name, age and salary// declare array of staff

}age and salary.

Page 31: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

31

Array of class : Exampley p2 methods to call member function for manager array.

1 By using array subscript in order to access manager in certain 1. By using array subscript in order to access manager in certain location of the array. cin >> n ; manager[n].read_data() ;

t [ ] [ ] cout << manager[n].name << manager[n].age ; manager[n].print_data() ;

• 2. By using loop in order to access a group of managers // read information for 10 managers for ( int x = 0 ; x < 10; x++ )

manager[x].read_data() ; // print information of 10 managers for ( int y = 0 ; y < 10; y++ )

manager[y].print_data()

Page 32: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

32

Pass array of object to function: ExampleExample

class info {

main() { info data[10]; for (int n = 0; n < 5; n++){{

private: char medicine[15]; char disease[15];

public: id d() { i di i }

{ data[n].setMedicine); data[n].setDisease();

} cout <<"\nList of disease and

i ivoid setMed() { cin >> medicine;} void setDisease() { cin >> disease;} char*getMedicine(){return medicine;} char* getDisease() {return disease;} };

medicine"; for (int n = 0; n < 5; n++) cout << "\n" << data[n].getMedicine() << data[n].getDisease(); }; [ ] g ();// pass the whole array to functioncheckMedicine(data); getch(); }Class info store information about

disease and the relevant medicine

Page 33: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

33

Pass array of object to function: ExampleExample

• checkMedicine(data) function receive an • checkMedicine(data) function receive an array of object info. This function require the user to enter the name of the disease. Based on user to enter the name of the disease. Based on the disease’s name, the function will search for the medicine that is suitable for the disease.

Page 34: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

34

Pass array of object to function:y jvoid checkMedicine(info x[]) { char diseas[20]; int found = 0; cout << "\nEnter the disease name: ";

checkMedicine(data);Call this function, where data is an array of objects from class info. cout << "\nEnter the disease name: ";

cin >> diseas; for (int n = 0; n < 5; n ++) if (strcmp(diseas, x[n].getDisease()) == 0 ){ cout << "\nMedicine for your disease: " << diseas << " is "

class info.

{ cout << "\nMedicine for your disease: " << diseas << " is " << x[n].getMedicine(); found = 1; break; }} if (found == 0) cout << "\nSorry, we cannot find the medicine for your disease. Please refer to other physician."; }}

Page 35: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

35

Pointer to Objectj

• Pointer – store address of a variable.Pointer can also store address of an object • Pointer can also store address of an object.

• Examplestudent student1; // create instance of studentstude t stude t ; // c eate sta ce o stude tstudent* studentPtr = &student1;

• Create a pointer variable studentPtr and initialize the pointer with the address of instance student1

Page 36: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

36

Pointer to Objectj

Method to access class member through pointer variable studentPtr :variable studentPtr :

1) (*studentPtr) print() 1) ( studentPtr).print() or

2) studentPtr ->print()

Page 37: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

37

Pointer to Object : Example// pointer to object void main()// p j#include <iostream.h>#include <string.h> class student{

i t

void main(){student student1("Ahmad", 123123); student student2("Abdullah", 234234);cout << “Address of the object";

private:char name[30]; unsigned long metricNo;public: // konstruktor 2 paramstudent(char* nama,unsigned long num)

cout << "\nAddress student1: " << &student1 << "\nAddress student2 : " << &student2;

student* ptr;{

no_metrik = num;strcpy(name, nama);

}void print()

student ptr; cout << "\n\nPointer value “; ptr = &student1; cout <<"\nPointer value for student1“

<< ptr;void print(){ cout <<“\nStudent’s name:“ << name;cout <<“\nStudent’s metric number:“

<< metricNo;}

ptr = &student2; cout <<"\nPointer value for student2“

<< ptr;ptr ->print();

}};

}

Page 38: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

38

Pointer to Objectj

PROGRAM OUTPUTdd f th bj tAddress of the object

Address student1: : 0x0012ff68Address student2: : 0x0012ff44Pointer valuePointer value Pointer value for student1: 0x0012ff68Pointer value for student2: 0x0012ff44Student’s name: AbdullahStudent s name: AbdullahStudent’s metric number: 234234

Page 39: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

39

Pointer to Objectj• We can also allocate memory for a pointer variable using

operator new W d f i i bl i • We can destroy memory for a pointer variable using operator delete

• Example:

void main(){

student *ptr = new student("Ahmad" 123123);student *ptr = new student("Ahmad", 123123);ptr -> print();delete(ptr);ptr = new student("Abdullah", 234234);ptr ->print();delete(ptr);

}

Page 40: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

40

Header File and Implementation Filep• To implement ADT C++ separate files into

header files and implementation files.header files and implementation files.• This way, programmers can use implementation

file without knowing how the member functions i l dare implemented.

• Each class definition is placed in a header file▫ Classname h▫ Classname.h

• The implementation of a class’s methods are placed in an implementation file▫ Classname.cpp

Page 41: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

41

The header file – Sphere.hp/** @file Sphere.h */const double PI = 3.14159;class Spherec ass Sp e e{public:

Sphere(); // Default constructorSphere(double initialRadius); // ConstructorSphere(double initialRadius); // Constructorvoid setRadius(double newRadius);double getRadius() const; // can’t change data membersdouble getDiameter() const;double getCircumference() const;double getCircumference() const;double getArea() const;double getVolume() const;void displayStatistics() const;

private:private:double theRadius; // data members should be private

}; // end Sphere

Page 42: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

42

The implementation file- Sphere.cpp/** @file Sphere.cpp */#include <iostream>#include "Sphere.h" // must include header file#include Sphere.h // must include header fileusing namespace std;Sphere::Sphere() : theRadius(1.0){} // end default constructor} // end default constructorSphere::Sphere(double initialRadius){

if (initialRadius > 0)if (initialRadius > 0)theRadius = initialRadius;

elsetheRadius = 1.0;

} // end constructor} // end constructor

Page 43: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

43

The implementation file-Sphere.cppvoid Sphere::setRadius(doublenewRadius)newRadius)

{if (newRadius > 0)

theRadius = newRadius;else

th R di 1 0theRadius = 1.0;} // end setRadius

• The constructor could call setRadius

Page 44: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

44

The implementation file-Sphere.cppdouble Sphere::getRadius() const{

return theRadius;} // end getRadius. . .. . .

double Sphere::getArea() const{{

return 4.0 * PI * theRadius * theRadius;

} // d tA} // end getArea. . .

Page 45: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

45

Client File: Using the class Sphere/* SphereDemo.cpp */#include <iostream>#include "Sphere.h" // must include header fileusing namespace std;int main() // the client{

Sphere unitSphere;Sphere mySphere(5.1);cout << mySphere.getDiameter()

<< endl;. . .

} // end main

Page 46: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

46

File Compilation and Executionp

Compile all

Sphere.hinclude include

p.cpp files separately in order to create

Sphere.cpp sphereDemo.cpp

compile compile

order to create object files. Link all files to

Object files for Sphere.cpp

Object files for SphereDemo.cpp

linkcreate .exe files.

link

Execution file

[email protected]

Page 47: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

47

Create File Project in Borland C++ EnvironmentEnvironmentSteps to create project file:

• Compile .cpp files separately. • Crete project file by choose the menu

<File> <New><Project>S t th j t tti f ll• Set the project setting as follows:

Project name : ProjectName.prj or ProjectName.ideTarget name: will create automaticallyTarget type: Application [.exe]Target type: Application [.exe]Platform : Win32Target model : ConsoleFrameworks/Control: Uncheck all the check boxes.Lib i St tiLibraries: StaticThen click OK.

Page 48: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

48

Create File Project in Borland C++ EnvironmentEnvironmentChoose the implementation file for the projects:

▫ Right click the mouse button on the ProjectName.exe . g b j▫ Delete all files in the list.▫ Choose <add node> and choose Sphere.cpp and ▫ Click <Open> button.▫ Choose <add node> and choose SphereDemo cpp andChoose <add node> and choose SphereDemo.cpp and▫ Click <Open> button.

• Link all object files by clicking ProjectName.exe and choose menu <Project> <Compile>

then choose then choose <Project><Make all>.

• If there is a linker error, debug the error and link the files again. • The execution file will be generated when all errors have been

d b debug. • Run the execution file by choosing <Debug> and <Run>.

Page 49: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

49

ConclusionIn this class you have learned about:• Data Abstraction ConceptData Abstraction Concept• Review C++ concept:▫ Declaring a class, data member and function member

C ti t t d d t t▫ Creating constructor and destructor▫ Create object as function parameter▫ Return object from a functionj▫ Array of class & Pointer to class▫ Define and implement a class within header files and

implementation filesp▫ Welcome to Data Structure class

Page 50: Abstract Data Type.ppt - Universiti Teknologi Malaysia · • Abstract data type (ADT) An ADT is composed of xA collection of data xA set of operations on that data S ifi i f ADT

7/6/[email protected]

50

References

1. Frank M. Carano, Data Abstraction and problem solving with C++ Walls and Mirrors problem solving with C++. Walls and Mirrors. 2008.

2. Nor Bahiah et al. Struktur data & algoritma2. Nor Bahiah et al. Struktur data & algoritmamenggunakan C++. Penerbit UTM, 2005