1 / 30

Chapter 10

Chapter 10. Defining Classes. User-defined Types. Are data types defined by programmers. Include: typedef : simple data definition struct : a structure composed of data members that are different types.

tuari
Download Presentation

Chapter 10

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10 Defining Classes

  2. User-defined Types • Are data types defined by programmers. • Include: • typedef: simple data definition • struct: a structure composed of data members that are different types. • class: an extension of struct. It contains both data members (attributes) and member functions (methods).

  3. Structures • Is a data type composed of data members that are different types. • Defining syntax: structstructName { type data1; type data2; … type dataN; }; • Declaration syntax: structNamevarName;

  4. Structure defintition struct STime { int hour; int minute; int second; }; STime lunchTime, classTime; struct SDate { int year; int month; int day; } myBirthDay, laborDay; Separate variable declarations Combine with variable declarations (Directly declare)

  5. Notes for structure defintition • Structure definitions do not allocate space. Space is allocated when a structure variable is defined. • Since different compilers allocate filler space between fields differently, use the sizeof() operator to determine structure size for space allocation. • sizeof(n) - operator returns the number of bytes needed to store an object. It is machine dependent. • DO NOT FORGET THE SEMICOLON AFTER THE DECLARATION!!! • Two different structures can have data members with the same name struct Fertilizer struct Crop { { double quantity; double quantity; double nitrogen; double size; }; };

  6. The Dot . operator • Used to access data members. • Has highest precedence. • Ex: structSTime { int hour; int minute; int second; }; void main () { STimeclassTime; cout << "Enter the class time as hours, minutes and seconds, separate by spaces: “; cin >> classTime.hour >> classTime.minute >> classTime.second; classTime.hour--; // Set it to one hour early cout << "The updated class time is " << classTime.hour << " hours, "; cout << classTime.minute << "minute(s) and " << classTime.second << " second(s)\n"; }

  7. Initializing Structures • Can initialize a structure variable when it is declared. SDate taxDate = {2013, 4, 15}; // year = 2013, month = 4, day = 15 • Initializing values must be given in order that corresponses to the order of data members in the structure definition. SDate taxDate = {4, 15, 2013}; // year = 4, month = 15, day = 2013 SDate taxDate = {2013}; // year = 2013, month = 0, day = 0 SDate taxDate = {2013, 15}; // year = 2013, month = 15, day = 0 SDate taxDate = {2013, 4, 15, 3}; // syntax error

  8. Hierarchical Structures • Structures cannot contain an instance of itself (defined recursively) • However, structures can contain other structures (nested structures). struct SDate { int year; int month; int day; }; struct SStudentInfo { char name; SDate bDay; double gpa; };

  9. Advantages of Hierarchical Structures • Separated structure can be used in one program for different purposes. • Ex: read in a day into SDate thisday and then search record for persons with this birthday and send card. • Structure is a collection of related information. So, it is considered one entity when hierarchically used inside other structures. • Ex: It is clear that month, day and year are one entity (SDate). Details of month, day and year are pushed to lower level. We are not concerned with their structure until we actually need to use them.

  10. Access hierarchical structure members • Used applicable dot operations. • Ex: struct SDate { int year, month, day; }; struct SStudentInfo { char name; SDate bDay; double gpa; }; void main () { SStudentInfo JohnDoe = {“John Doe”, {1990, 12, 31}, 3.50}; SStudentInfo anotherStudent; char first[15], last[15]; cout << "Enter the student first name and last name separated by a space: " cin >> first >> last; strcat (first, last); strcpy (anotherStudent.name, first); cout << "Enter the student birthdays (in order of year, month and day), separated by spaces : " cin >> anotherStudent .bDay .year>> anotherStudent .bDay .month>> anotherStudent .bDay .day; cout << “John Doe’s birthday is: ” << JohnDoe .bDay .month<< “/” << JohnDoe .bDay .day<< “/”<< JohnDoe .bDay .year << endl; }

  11. Assignment Operator in Structure • Used to assign value of one structure variable to another. • Assigns each data member of the right side to its corresponding data member on the left side matched. • Ex: SDate myBD = {1900, 12, 31}; SDate yourBD = myBD; // Your BD is now 12/31/1900 SStudentInfo aStudent; aStudent.bDay = myBD;

  12. Structures and Arrays • Structures contain arrays: struct SStudentInfo { char name; SDate bDay; float quiz[5]; }; SStudentInfo aStudents; cout << aStudents.name; cout << aStudents.quiz[1]; • An array of structures: SStudentInfo csci123Students[25]; cout << csci123Students[2].name; cout << csci123Students[2].bDay.year; csci123Students[2].quiz[3] = 9.5;

  13. Classes • An extension of struct: It contains both data members (attributes) and member functions (methods). • The first characteristic of classes is encapsulation. • Encapsulation: the binding together of data and functions into a single entity (object). This allows the object to be used in different applications because its data parts are defined and the behaviors it can do (member functions) are defined. It is a known quantity—just like we know how integers behave and what they contain! • Includes 2main parts: definition and implementation

  14. Class definition • consists of specifications of data members (variable, constants, types) and member function prototypes. • The prototypes in the public section are all the programmer needs. • Usually stored in the header file (ClassName.h) • Usually has 2 sections: public and private. • Might have another section: protected.

  15. Class definition (example) class CDate { public: CDate(); // default constructor CDate(int m, int d, int y); // parameterized constructor CDate(const CDate& aDay); // copying constructor ~CDate(); // destructor int getMonth(); // accessor int getDay(); // accessor void setMonth(int m); // mutator void setDay(int d); // mutator void display(); // a member function int year; private: int month; int day; bool isValid(); };

  16. Class public and private sections • Public section: • It tells users what an object of the class can do. • Anything defined in the public section can be seen and used by other parts of the program. • Private section: • Hidden from users. • Includes local data members and functions used only in the class implementation. • Private data members can only be changed by member functions. This prevents the object from being changed illegally by the application program.

  17. Class implementation • contains the member function definitions. This is the procedural abstraction of the class. • It could be stored below main or in a .cpp file since it is executable C++ code. • However, it is usually stored in the class implementation file (ClassName.cpp)

  18. Class implementation (example) int CDate::getMonth() { return month; } int CDate::getDay() { return day; } void CDate::setMonth(int m) { month = m; } void CDate::setDay(int d) { day = d; } void CDate::display() { cout << month <<'/' << day << '/' << year; } boolCDate::isValid () { return (month > 0 && month < 13) && (day > 0 && day < 32) && (year > 0); } #include "Date.h" CDate::CDate () { month = 1; day = 1; year = 1900; } CDate::CDate (int m, int d, int y) { month = m; day = d; year = y; } CDate::CDate (const CDate& aDay) { month = aDay.month; day = aDay.day; year = aDay.year; } CDate::~CDate () {}

  19. Class implementation (example) int CDate::getDay() { return day; } void CDate::setMonth(int m) { month = m; } void CDate::setDay(int d) { day = d; } void CDate::display() { if (isValid()) cout << month <<'/' << day << '/' << year; else cout << “Invalid date to display”; } boolCDate::isValid () { return (month > 0 && month < 13) && (day > 0 && day < 32) && (year > 0); } #include "Date.h" CDate::CDate () : month(1), day(1), year(1900) {} CDate::CDate (int m, int d, int y) : month(m), day(d), year(y) {} CDate::CDate (const CDate& aDay) : month(aDay.month), day(aDay.day), year(aDay.year) {} CDate::~CDate () {} int CDate::getMonth() { return month; }

  20. Class common operators • Scope resolution :: • tells the compiler that this function is a member of the class (classname::functionname). • Dot operator . • tells the compiler to go to the class definition for this object and use the function defined in that class object.functionname(parameters). • Assignment operator = • Like a struct, the assignment operation assigns each data member of the right side to its corresponding data member on the left side matched

  21. Accessor and Mutator functions • Assessor functions: Since the application can’t see the private data members of a class, the class must provide public functions that return the private data. Functions that are public and allow access to the member variables are called accessor functions. • Ex: getMonth(), getDay() • Mutator Functions: Functions that allow the changing of private data members. • Ex: setMonth(), setDay();

  22. Class object initialization • The assumption in classes is that we wouldn’t declare an object unless we wanted to put meaningful data in it. • If we do not tell the compiler what information to put in the object, the object will contain garbage. • Therefore, we need to create an automatic function that will create an object containing valid data. That function is called constructor.

  23. Constructor • A function which creates and initializes an object • Has the same name as the class name. • Associates an initializing function with the class object (instance, variable). • Does not return a type or use the word void • Declared in public section.

  24. Constructor types • Constructor sets initial values 3 ways: • Default constructor: sets to base value. Only 1. • Paramertized constructor: gets values from parameter list. Can have 1 or more. • Copy constructor: copies one object into another. Only 1.

  25. Constructor Notes • Every class must have at least a default constructor • The constructor function is called every time an object is declared. This insures that an object does not have garbage in it. • Initializers can be used within the constructor. CDate myBD(12, 31, 1999); • A constructor can be explicitly called. CDate hisBD = CDate (1, 1, 2000); • Do NOT use () when declaring an object if you want to use the default constructor for initialization: CDate yourBD(); // invalid code CDate yourBD; // OK

  26. Class Header and Implementation files • Classes are stored in 2 separate files: • .h file contains the definition section- user interface (class header file) • .cpp file contains the implementation section (class implementation file)

  27. Using #ifndef • Used to ensure that a header file has not already been included resulting in duplicate copies of the class. • States that the header file is not defined previously then use this definition--otherwise, do not include the class again. // Date.h #ifndef _DATE_H_ #define _DATE_H_ #include <iostream> … using namespace std; class CDate { … }; #endif // Date.cpp #include “Date.h” CDate::CDate () { month = 1; day = 1; year = 1900; } CDate::CDate (int m, int d, int y) { month = m; day = d; year = y; }

  28. Using newly defined class • Treat new class as new data type. • Use dot operator to access data members and member functions (class attributes and methods) #include “Date.h” using namespace std; void main () { CDate yourBD; cout << "Enter your birthday as month, day and year, separate by spaces: “; cin >> yourBD.month >> yourBD.day >> yourBD.year; // Syntax error } //Default constructor called Private data members

  29. Using newly defined class (cont.) #include “Date.h” using namespace std; void main () { CDate yourBD; cout << "Enter your birthday as month, day and year, separate by spaces: ”; int m, d; cin >> m >> d >> yourBD.year; yourBD.setMonth(m); yourBD.setDay(d); cout << “Your birthday is: " << yourBD.display() << endl; CDate LincohnBD(2, 12, 1809); cout << “Abraham Lincoln's birthday is: " << LincohnBD.display() << endl; CDate twinBrotherBD(yourBD); cout << “Your twin brother’s birthday is: " << twinBrotherBD.display(); } //Default constructor called //Parameterized constructor called //Copying constructor called Enter your birthday as month, day and year, separate by spaces: 8 31 2000 Your birthday is: 8/31/2000 Abraham Lincoln's birthday is: 2/12/1809 Your twin brother’s birthday is: 8/31/2000

  30. Abstract Data Types (ADT) • Data type: consists of a description of the data and the operations that can be performed on them. • Examples: complex numbers, vectors, points, matrices, shapes • Data abstraction: separation of logical properties of data structure from its implementation. • abstract data types(ADT): a model of a data type consisting of its attributes and its behavior(complex numbers) • information hiding: preventing the user from access to information that is internal to the functions/ data type. (i.e. local variables or functions which are submodules of higher functions) • Abstraction: High-level operations appropriate to the data type are isolated from the low-level implementation details associated with the data type. User is not concerned with how real numbers are stored or added by the computer, just that that operation exists-that is hidden from the user (data abstraction). • Ex: A circleclass would have an object (circle) and methods to draw, expand, contract, erase, etc. We don’t need to know how the circle is drawn or erased, just that we can do it and how to call the function.

More Related