Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2003 Prentice Hall, Inc. All rights reserved. 1 6.1 Introduction Object-oriented programming (OOP) –Encapsulates data (attributes) and functions (behavior)

Similar presentations


Presentation on theme: " 2003 Prentice Hall, Inc. All rights reserved. 1 6.1 Introduction Object-oriented programming (OOP) –Encapsulates data (attributes) and functions (behavior)"— Presentation transcript:

1  2003 Prentice Hall, Inc. All rights reserved. 1 6.1 Introduction Object-oriented programming (OOP) –Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding –Class objects communicate across well-defined interfaces –Implementation details hidden within classes themselves User-defined (programmer-defined) types: classes –Data (data members) –Functions (member functions or methods) –Similar to blueprints – reusable –Class instance: object

2 Structured Data Types ] struct = an abstract data type with a fixed number of components that are accessed by name, not by index.

3  2003 Prentice Hall, Inc. All rights reserved. 3 6.2 Structure Definitions Structures –Aggregate data types built using elements of other types struct Time { int hour; int minute; int second; }; Structure member naming –In same struct : must have unique names –In different struct s: can share name struct definition must end with semicolon Structure tag Structure members

4  2003 Prentice Hall, Inc. All rights reserved. 4 6.2 Structure Definitions Self-referential structure –Structure member cannot be instance of enclosing struct –Structure member can be pointer to instance of enclosing struct (self-referential structure) Used for linked lists, queues, stacks and trees struct definition –Creates new data type used to declare variables –Structure variables declared like variables of other types –Examples: Time timeObject; Time timeArray[ 10 ]; Time *timePtr; Time &timeRef = timeObject;

5  2003 Prentice Hall, Inc. All rights reserved. 5 6.3 Accessing Structure Members Member access operators –Dot operator (. ) for structure and class members –Arrow operator ( -> ) for structure and class members via pointer to object –Print member hour of timeObject : cout << timeObject.hour;

6 Can Assign Aggregate Values in the declaration Date myBirth = {2, 29, 1963}; Date today = {11, 25, 1999}; Date bill_Date = {3, 25, 2001}; Date lily_Bday = {1, 20, 1995};

7 Assigning Values myBirth. month = 2; myBirth. day = 29; myBirth. year = 1963; bill_Date.month = 3; bill_Date.day = 25; lily_Bday.year = 1995; today.month = 4; * instance of Date member of myBirth instance

8 Alternate assignments: struct { int month; int day; int year; } mybirth,billday,today; Variables of type struct struct Date { int month; int day; int year; }; Date mybirth, billday,today;

9  2003 Prentice Hall, Inc. All rights reserved. Structures as Arguments // in a prototype int Overdue(Date, int); * * * * // in a function call Overdue(today, bill_Date.year); // in a function header int Overdue(Date now, int purchased)

10  2003 Prentice Hall, Inc. All rights reserved. Aggregate Operations OperationArrays Structs I/ONo ( except strings )No AssignmentNo Yes ArithmeticNo No ComparisonNo No Parameter pass.Ref. only Either value or ref. Funct. return value No Yes

11  2003 Prentice Hall, Inc. All rights reserved. 11 6.4 Implementing a User-Defined Type Time with a struct Default: structures passed by value –Pass structure by reference Avoid overhead of copying structure C-style structures –No “interface” If implementation changes, all programs using that struct must change accordingly –Cannot print as unit Must print/format member by member –Cannot compare in entirety Must compare member by member

12  2003 Prentice Hall, Inc. All rights reserved. Outline 12 fig06_01.cpp (1 of 3) 1 // Fig. 6.1: fig06_01.cpp 2 // Create a structure, set its members, and print it. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setfill; 11 using std::setw; 12 13 // structure definition 14 struct Time { 15 int hour; // 0-23 (24-hour clock format) 16 int minute; // 0-59 17 int second; // 0-59 18 19 }; // end struct Time 20 21 void printUniversal( const Time & ); // prototype 22 void printStandard( const Time & ); // prototype 23 Define structure type Time with three integer members. Pass references to constant Time objects to eliminate copying overhead.

13  2003 Prentice Hall, Inc. All rights reserved. Outline 13 fig06_01.cpp (2 of 3) 24 int main() 25 { 26 Time dinnerTime; // variable of new type Time 27 28 dinnerTime.hour = 18; // set hour member of dinnerTime 29 dinnerTime.minute = 30; // set minute member of dinnerTime 30 dinnerTime.second = 0; // set second member of dinnerTime 31 32 cout << "Dinner will be held at "; 33 printUniversal( dinnerTime ); 34 cout << " universal time,\nwhich is "; 35 printStandard( dinnerTime ); 36 cout << " standard time.\n"; 37 38 dinnerTime.hour = 29; // set hour to invalid value 39 dinnerTime.minute = 73; // set minute to invalid value 40 41 cout << "\nTime with invalid values: "; 42 printUniversal( dinnerTime ); 43 cout << endl; 44 45 return 0; 46 47 } // end main 48 Use dot operator to initialize structure members. Direct access to data allows assignment of bad values.

14  2003 Prentice Hall, Inc. All rights reserved. Outline 14 fig06_01.cpp (3 of 3) fig06_01.cpp output (1 of 1) 49 // print time in universal-time format 50 void printUniversal( const Time &t ) 51 { 52 cout << setfill( '0' ) << setw( 2 ) << t.hour << ":" 53 << setw( 2 ) << t.minute << ":" 54 << setw( 2 ) << t.second; 55 56 } // end function printUniversal 57 58 // print time in standard-time format 59 void printStandard( const Time &t ) 60 { 61 cout << ( ( t.hour == 0 || t.hour == 12 ) ? 62 12 : t.hour % 12 ) << ":" << setfill( '0' ) 63 << setw( 2 ) << t.minute << ":" 64 << setw( 2 ) << t.second 65 << ( t.hour < 12 ? " AM" : " PM" ); 66 67 } // end function printStandard Dinner will be held at 18:30:00 universal time, which is 6:30:00 PM standard time. Time with invalid values: 29:73:00 Use parameterized stream manipulator setfill. Use dot operator to access data members.

15 Arrays of Structures struct Salaried { char dept[5]; int salary; int vac_days; }; // array of 20 elements, each of type Salaried Salaried emp[20];

16 Arrays of Structures emp[0].dept = “Purc”; emp[0].salary = 34560; emp[0].vac_days = 14;... emp[2].salary = 32100; emp[2].dept = “Ship”; emp[2].vac_days = 10; … emp[19].dept = “Acct”; emp[19].salary = 22500; emp[19].vac_days = 12;

17 Arrays of Structures struct Payroll { int id; char name[15]; double payrate; }; // an array of 3 records of type Payroll Payroll employee[3];

18 Arrays of Structures // load array -- there are other ways to load the array Payroll employee[3] = { {11, “Mickey”, 7.25}, {12, “Minny”, 6.50}, {13, “Donald”, 9.00} }; // display array for(ndx = 0; ndx < 3; ndx++) cout << ‘\n’ << employee[ndx].id << setw(20) << employee[ndx].name << setw(20) << employee[ndx].payrate;

19 Arrays of Structures int main() { //declare array of 3 records of type Payroll // and initialize the first record Payroll employee[3] = { 11, “Mickey", 7.25 }; loadarray(employee);// calls showarray(employee); cout << endl<<endl;// for formatting } // end main()

20 Arrays of Structures // load array - data typically entered via file input void loadarray(Payroll staff[3]) { // begin at 1 because [0] already entered for(int ndx = 1; ndx < 3; ndx++) { cout << "Enter the ID, name, and pay rate: "; cin >> staff[ndx].id >> staff[ndx].name >> staff[ndx].payrate; cout << endl; } }

21 Nested Structures struct Date {int month; int day; int year; }; struct vital_Data {char name[15]; char owner[10]; int ID; Date birth; // Date must be previously defined double strength; }; *

22 Nested Structures // declaration of an object vital_Data Digimon; // declaration of an object // assignments of data to an object strcpy(Digimon.name,“wormmon”); strcpy(Digimon.owner,“ken”); Digimon.ID = 1234; Digimon.birth.day= 10;// this is a struct Digimon.evolution = 12.75;

23 #include using namespace std; struct Employee { int idNum; double payRate; double hours; }; Employee getValues(); int main() { Employee emp; emp = getValues(); cout << "\nThe employee id number is " << emp.idNum << "\nThe employee pay rate is $" << emp.payRate << "\nThe employee hours are " << emp.hours << endl; return 0; } //return a struct Employee getValues() { Employee next; next.idNum = 6789; next.payRate = 16.25; next.hours = 38.0; return next; }

24  2003 Prentice Hall, Inc. All rights reserved. 24 Pointers to structures –Print member hour of timeObject : cout << timeObject.hour; OR timePtr = &timeObject; cout hour; –timePtr->hour same as ( *timePtr ).hour Parentheses required –* lower precedence than.

25 Pointers to Structures struct Employee { int idNum; double payRate; double hours; } Employee *pt; (*pt).idnum pt->idnum “the structure whose address is in pt” (*pt).payRate pt->payRate (*pt).hours pt->hours Alternate notation Use: Declaration:

26  2003 Prentice Hall, Inc. All rights reserved. 26 Structures which include self referential pointers For linked lists

27 Self referential structures The records are linked by including the address of the next record (I.e. a pointer). struct Beers { char beername[10]; Beer *nextbeer; } Pointer to another structure

28 Main () { Beer t1 = {“bud”}; Beer t2 = {“miller”}; Beer t3 = {“coors”}; Beer *first; first = &t1; t1.nextbeer = &t2; t2.nextbeer = &t3; t3.nextbeer = NULL; //sets pointer to zero cout beername name name; Bud 0xff1Miller 0xaf3Coors \0 0xff1 0xaf3 t1 t2 t3 0xaaa first 0xaaa

29 Bud 0xff1Miller 0xaf3Coors \0 0xff1 0xaf3 t1 t2 t3 0xaaa first 0xaaa first = first->nextbeer; cout beername<<endl; first = first->nextbeer; cout beername<<endl; first = first->nextbeer; cout beername<<endl; \0 0xff10xaf3 ****

30 4 p,x 7 NULL q,y el next struct nodetype { int el; nodetype *next; }; nodetype *p, *q, x,y,z; p= &x; p->el = 4; q = &y; q->el = 7; q->next = NULL; p->next = q; cout el << endl; p=p->next; cout el << endl; q 4 7 NULL p q 4 p ***

31 Dynamic allocation new reserves the number of bytes required by the requested data type and returns the address of the first reserved location or NULL if there is no memory delete releases the block of bytes

32 (1) p = new nodetype; (2) q = p; (3) p->el = 4; (4) r = new nodetype; (5) r->el = 9; (6) s = new nodetype; (7) s->el = q->el + p->el; (8) p->next = r; (9) r->next = s; (10) r->el = 3.0; (11) s=p; (12) q = q->next; (13) q->el = 6.0; (14) q = q->next; (15) cout el << endl; (16) cout el << endl; (17) cout el << endl; (18) cout el << endl; p q 4 |9 | r 13 | s s p q 4 |3 | r 8 | s p 4 |6 | r q 8 | q s p 4 |6 | r 8 | final *****


Download ppt " 2003 Prentice Hall, Inc. All rights reserved. 1 6.1 Introduction Object-oriented programming (OOP) –Encapsulates data (attributes) and functions (behavior)"

Similar presentations


Ads by Google