chapter 10 defining classes. user-defined types are data types defined by programmers. include: –...

30
Chapter 10 Defining Classes

Upload: lee-burke

Post on 26-Dec-2015

237 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

Chapter 10

Defining Classes

Page 2: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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).

Page 3: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

Structures• Is a data type composed of data members that

are different types.• Defining syntax:

struct structName {

type data1;type data2;…type dataN;

};

• Declaration syntax:structName varName;

Page 4: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

Structure defintitionstruct 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)

Page 5: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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;

}; };

Page 6: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

The Dot . operator• Used to access data members.• Has highest precedence.• Ex:

struct STime{

int hour;int minute;int second;

};

void main (){

STime classTime;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 earlycout << "The updated class time is " << classTime.hour << " hours, ";cout << classTime.minute << "minute(s) and " << classTime.second << " second(s)\n";

}

Page 7: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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 = 2013SDate taxDate = {2013}; // year = 2013, month = 0, day = 0SDate taxDate = {2013, 15}; // year = 2013, month = 15, day = 0SDate taxDate = {2013, 4, 15, 3}; // syntax error

Page 8: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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;

};

Page 9: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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.

Page 10: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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;}

Page 11: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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/1900SStudentInfo aStudent;aStudent.bDay = myBD;

Page 12: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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;

Page 13: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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

Page 14: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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.

Page 15: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

Class definition (example)class CDate{public:

CDate(); // default constructorCDate(int m, int d, int y); // parameterized constructorCDate(const CDate& aDay); // copying constructor~CDate(); // destructor

int getMonth(); // accessorint getDay(); // accessorvoid setMonth(int m); // mutatorvoid setDay(int d); // mutator

void display(); // a member function

int year;private:

int month;int day;bool isValid();

};

Page 16: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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.

Page 17: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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)

Page 18: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

Class implementation (example)#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;}

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;}bool CDate::isValid (){ return (month > 0 && month < 13) && (day > 0 && day < 32) && (year > 0);}

Page 19: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

Class implementation (example)#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;}

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”;}

bool CDate::isValid (){ return (month > 0 && month < 13) && (day > 0 && day < 32) && (year > 0);}

Page 20: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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

Page 21: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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();

Page 22: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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.

Page 23: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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.

Page 24: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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.

Page 25: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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 codeCDate yourBD; // OK

Page 26: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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)

Page 27: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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;

}

Page 28: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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

Page 29: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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();

}

Enter your birthday as month, day and year, separate by spaces: 8 31 2000Your birthday is: 8/31/2000Abraham Lincoln's birthday is: 2/12/1809Your twin brother’s birthday is: 8/31/2000

//Default constructor called

//Parameterized constructor called

//Copying constructor called

Page 30: Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure

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 circle class 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.