11/03/08met cs 563 - fall 2008 7. structures and classes 1 7. implementing objects with struct and...

26
11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with 7. Implementing Objects with struct struct and and class class 7.1. Structures—Implementing Objects 7.1. Structures—Implementing Objects with with struct struct Definition Access: members, initialization, assignment Structures as arguments to functions 7.2. Classes— Implementing Objects with Implementing Objects with class class Definition: add object behavior Constructors for Creating and Initializing class Objects Access: Private and Public Members, Calling Member Functions Assigning class Objects Encapsulation, Information Hiding, and Message Passing.

Post on 20-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

1

7. Implementing Objects with 7. Implementing Objects with structstruct and and classclass

7.1. Structures—Implementing Objects with 7.1. Structures—Implementing Objects with structstructDefinition Access: members, initialization, assignment Structures as arguments to functions

7.2. Classes—Implementing Objects with Implementing Objects with classclass Definition: add object behavior Constructors for Creating and Initializing class Objects Access: Private and Public Members, Calling Member Functions Assigning class Objects Encapsulation, Information Hiding, and Message Passing.

Page 2: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

2

7.1. Structures7.1. Structures - - (i) Definition(i) Definition

defines type DateStruct

declares object (holiday) and pointer to object (dayPtr) of type DateStruct in the usual way

Syntax of Type Definition:Syntax of Type Definition:

struct <type-name> type-name> {{ <member-declaration>… <member-declaration>…}

keyword

members of the DateStruct type

Example:Example:struct DateStruct {

int month; // 1-12int day; // 1-31int year; // >= 1

};

DateStruct holiday, *dayPtr;

Note the difference to C: no type definition with Note the difference to C: no type definition with typedeftypedef needed, i.e. needed, i.e. structstruct defines a type defines a type directly directly

Page 3: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

3

(ii) Accessing Structure Members(ii) Accessing Structure Members

parameterized stream manipulators setiosflags(), setw() must be repeated in next cout (D&D, Ch.12.6-7)

object name and dot operator ( . )< object-name> . <member-name> Example:Example:DateStruct today; DateStruct today; today.month=6;today.month=6;today.day=5;today.day=5;today.year=2000;today.year=2000;cout << "Today is the";cout << "Today is the";cout<<setiosflags(ios::fixed|ios::right) cout<<setiosflags(ios::fixed|ios::right)

<<setw(3)<< <<setw(3)<< today.monthtoday.month <<"," <<","<<setw(3)<< <<setw(3)<< today.daytoday.day <<"," <<","<<setw(5)<< <<setw(5)<< today.yeartoday.year <<endl; <<endl;

pointer name and arrow operator ( -> )

< object-name> -> < member-name> Example:Example:DateStruct *dayPtr=&today; DateStruct *dayPtr=&today; cout<<"dayPtr points to today: \n";cout<<"dayPtr points to today: \n";cout<<setiosflags(ios::fixed|ios::right)cout<<setiosflags(ios::fixed|ios::right)

<<setw(3)<< <<setw(3)<< dayPtr->monthdayPtr->month <<"," <<","<<setw(3)<< <<setw(3)<< dayPtr-> daydayPtr-> day <<"," <<","<<setw(5)<< <<setw(5)<< dayPtr-> yeardayPtr-> year <<endl; <<endl;

Today is the 6, 5, 2000dayPtr points to today: 6, 5, 2000

Page 4: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

4

(iii) Initializing and Assigning Structures(iii) Initializing and Assigning Structures

Structures can be assigned directly to one another

< object-name1> = < object-name2> Example:Example:anotherDay = today;anotherDay = today;cout<<"anotherDay is assigned the value of today. anotherDay is: \n";cout<<"anotherDay is assigned the value of today. anotherDay is: \n";cout << …cout << …

anotherDay is assigned the value of today. anotherDay is: 6, 5, 2000

Initialization is similar to array initialization

< object-name> { <value>, <value>, …}Example:Example:DateStruct *dayPtr, aDay={1, 3, 1978} ;dayPtr = &aDay;cout<<"dayPtr points to aDay: \n";cout<<…

dayPtr points to aDay: 1, 3, 1978

Page 5: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

5

(iv) (iv) Structures as arguments to functions are passed by

value Pass by value means that a copy of the entire structure is passed to the function. The actual argument in the calling environment is not changed, even if its copy in the function has been changed.

Problem:Problem: How to avoid the copying of the structure and thus the waste of memory (similar to pass by reference) and still shelter the calling environment by not allowing changes of the actual arguments even if they have been changed in the function (similar to pass by value)

Solution:Solution: Pass by constant reference, making the argument constant, i.e. disallowing changes and at the same time a reference parameter

Example:Example: Function taking a DateStruct object and returning the next day of the object will have as prototype

DateStruct nextDay ( const DateStruct & );

Page 6: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

6

Figure 7.1a: function nextDay() - overviewFigure 7.1a: function nextDay() - overview

DateStruct nextDay(const DateStruct& aDay )// Advances to next day// Receives: aDay of type DateStruct by constand reference// Returns: next day's value of type DateStruct{

DateStruct next=aDay; next.day++;

switch(next.month){

}

31-day months

30-day months

December - New Year

February - leap years

Page 7: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

7

Figure 7.1b: function nextDay(), 31- and 30- day months and DecemberFigure 7.1b: function nextDay(), 31- and 30- day months and December

case 1: case 3: case 5: case 7:case 8: case 10:

if(next.day == 32){next.day = 1;next.month++;

}return next; break;

case 12: if(next.day == 32){

next.day = 1;next.month = 1;

next.year++;} return next; break;

New Year: set month to 1

case 4: case 6: case 9: case 11:if(next.day == 31){

next.day = 1;next.month++;

} return next; break;

next month:increment month by 1

Page 8: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

8

Figure 7.1c: function nextDay(), FebruaryFigure 7.1c: function nextDay(), February

case 2: //February//leap year iff divisible by 4, but not divisible by 100, unless divisible by 400 too.*//The condition for a non leap is then:

if(next.day>29 || next.day==29 &&((next.year %4 >0 || next.year % 100 == 0) && next.year % 400 > 0)){next.day = 1;next.month++;

} return next;break;

* The leap year will test true for the condition

(year % 4 == 0 ) && (year % 100 >0) || (year % 4 == 0 ) && (year % 400 == 0) (year % 4 == 0 ) && ((year % 100 >0) || (year % 400 == 0))

The condition in the if-statement is the negation of the above expression

Page 9: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

9

Structures - Summary• Defined with the struct keyword and allow implementation of user-

defined types that group, encapsulate, multiple member objects of different types;

• Declaration is as for the basic data types

• Assignment is as for the basic data types

• Initialization is similar to the one of arrays

• Structures are passed to functions by value (unlike arrays)

• Members are freely accessible within the scope of the structure through object name and dot operator (.) or through pointer and arrow operator (->)

Wishes: Wishes: • Group object behavior with the object, instead of having

unrelated separate functions;• Hide all implementation details that are irrelevant for the use of

the object so that user needs to worry only about how to manipulate object, not how it has been implemented (which he does not care about anyway).

classes

Page 10: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

10

7.2. Classes7.2. Classes - -(i) Class Type Definition(i) Class Type Definition

Main Idea: Adding what the object Main Idea: Adding what the object can docan do, i.e. object behavior, to , i.e. object behavior, to what object what object knowsknows, i.e. object data and internal computations. Or, i.e. object data and internal computations. OrEncapsulating object behavior and object dataEncapsulating object behavior and object dataExample:Example:DateBehavior/Interface (Algorithms, Functions, Methods)

Initialize itself to a particular date Tell its dayTell its monthTell its yearAdvance to the next day

Data/AttributesIts dayIts month

Its year

Interface with outside world through functions that are available publicly

Data or functions the objects knows or performs privately

Page 11: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

11

Class Type Definition - Date ExampleClass Type Definition - Date Example

Example:Example:class Date{public:

Date(int=0, int=0, int=0); //MS Visual C++ requires defaults

int theDay() const;int theMonth() const;int theYear() const;void advance();

private:int day; // 1-31int month; // 1-12int year; // >= 1 };

defines the class data type Date

keywords member functions or methods with which object communicates/interfaces with other objects, e.g. access/change the data members, check predicates

member data or functions, referred to as utility functions, that are not part of the object interface, but are used by methods for computations

Constructor prototype: special member function for initializing class objects. Must have: same name as class type no return type

Page 12: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

12

Class Type Definition Class Type Definition - Syntax- Syntax

class class <ClassName> {

public:

<ClassName>( <argumentList> );

<method1> ( <argumentList> );

<method2> ( <argumentList> );

private:

<dataType1> <dataMemberName1> ;

<dataType2> <dataMemberName2> ;

<utility function> ( <argumentList> );

}

Constructor: special member function to initialize objects of the type. Must have: same name as class type no return type

member functions or methods with which object communicates/interfaces with other objects, e.g. access/change the data members, check predicates

member data or functions, referred to as utility functions, that are not part of the object interface, but are used by the class methods for computations

Page 13: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

13

// Fig. 7.2a: Date class methods - theDay(), theMonth(), theYear()

int Date :: theDay() const

{return day;

}

Similarly

int Date :: theMonth() const{

return month;}

int Date :: theYear() const{

return year;}

Scope Resolution OperatorClass name

return type

Page 14: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

14

// Fig. 7.2b: Date class methods - advance() overview

void Date ::advance(){

day++;

switch(month){

}

31-day months

30-day months

December - New Year

February - leap years

Page 15: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

15

// Fig. 7.2c : Date class methods - advance(), 31- and 30- day months 31- and 30- day months and Decemberand December

case 1: case 3: case 5: case 7: case 8: case 10:if(day == 32){

day = 1;month++;

} break;

case 4: case 6: case 9: case 11:if(day == 31){

day = 1;month++;

} break;

case 12: if(day == 32){

day = 1;month = 1;year++;

} break;

Increment month by 1depending on days in month

New Year: increment year by 1

Page 16: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

16

// Fig. 7.2d : Date class methods - advance(), Februaryebruary

case 2: //February //leap year iff divisible by 4 //but not divisible by 100 //unless divisible by 400 too

if(day>29 || day==29 &&((year % 4 > 0 || year % 100 == 0) && year % 400 > 0)){day = 1;month++;

} break;

Page 17: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

17

Defining Methods - Syntax

<returnType> <className> :: <methodName> (<argumentList> )

{….

}

Scope Resolution Operator

function body

Page 18: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

18

Constructors Constructors

Definition:Definition: Any method with no return type (not even void) and the same name as the name of the class is a constructor

a) Constructor definition: function style

<className> :: < className > (<argumentList> )

{ <dataMember> = <argument> ;

}

Example:Example:

Date::Date(int d, int m, int y){day = d;month = m;year = y;

}

Goal:Goal: Provide a general way for initializing instances of a class.Solution in C++:Solution in C++: a special member function, called constructor, that is automatically invoked when an object of the class is created

Scope Resolution Operator

function body

Page 19: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

19

<className> :: < className > (<argumentList> ):

<dataMember> ( <argument> ) , …, <dataMember> ( <argument> ) {} ;

Example:Example:

Date :: Date(int d, int m, int y): day(d), month(m), year(y) {} ;

b) Constructor definition with initialization lists

initialization list empty function body

Page 20: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

20

(ii) Declaring (ii) Declaring class class Type Objects - similar to declaring basic data type objectType Objects - similar to declaring basic data type object

Examples:Examples:

Date holiday(4,7,2000), today;

Date *dayPtr;

day 4month 7year 2000

holiday

day 0month 0year 0

today

day month

year

dayPtr

Terminology:Terminology: Class data objects are instances of the class and their declaration is also called instantiation of class objects.

?

Page 21: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

21

(iii) Accessing class Members Through Methods(iii) Accessing class Members Through Methods

object name and dot operator ( . )< objectName> . <methodName> Example:Example:Date holiday(4,7,2000), today;Date holiday(4,7,2000), today;cout << "Holiday:";cout << "Holiday:";cout<<setiosflags(ios::fixed|ios::right)cout<<setiosflags(ios::fixed|ios::right)

<<setw(3)<<holiday.theMonth()<<","<<setw(3)<<holiday.theMonth()<<","<<setw(3)<<holiday.theDay()<<","<<setw(3)<<holiday.theDay()<<","

<<setw(5)<<holiday.theYear()<<endl;<<setw(5)<<holiday.theYear()<<endl;

today = Date(5,6,2000);today = Date(5,6,2000);cout << "Today is the";cout << "Today is the";cout<<setiosflags(ios::fixed|ios::right)cout<<setiosflags(ios::fixed|ios::right)

<<setw(3)<<today.theMonth()<<","<<setw(3)<<today.theMonth()<<","<<setw(3)<<today.theDay()<<","<<setw(3)<<today.theDay()<<","

<<setw(5)<<today.theYear()<<endl;<<setw(5)<<today.theYear()<<endl;Holiday: 7, 4, 2000Today is the 6, 5, 2000

pointer name and arrow operator ( -> )

< objPointerName> -> <methodName> Example:Example:Date *dayPtr, aDay; Date *dayPtr, aDay; dayPtr = &Date(1,3,1978);dayPtr = &Date(1,3,1978);cout<<setiosflags(ios::fixed|ios::right) cout<<setiosflags(ios::fixed|ios::right) <<setw(3)<<dayPtr->theMonth()<<","<<setw(3)<<dayPtr->theMonth()<<"," <<setw(3)<<dayPtr->theDay()<<","<<setw(3)<<dayPtr->theDay()<<"," <<setw(5)<<dayPtr->theYear()<<endl;<<setw(5)<<dayPtr->theYear()<<endl;aDay = *dayPtr;aDay = *dayPtr;cout<<setiosflags(ios::fixed|ios::right)cout<<setiosflags(ios::fixed|ios::right)

<<setw(3)<<aDay.theMonth()<<","<<setw(3)<<aDay.theMonth()<<","<<setw(3)<<aDay.theDay()<<","<<setw(3)<<aDay.theDay()<<","<<setw(5)<<aDay.theYear()<<endl;<<setw(5)<<aDay.theYear()<<endl;

3, 1, 1978 3, 1, 1978

literal

Page 22: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

22

Private vs. Public AccessPrivate vs. Public Access

Private class members cannot be accessed outside the object even if the object is in scope, e.g. holiday is in scope in main, but

holiday.day;holiday.month; are illegal in main!!!are illegal in main!!!holiday.year;

Public members provide the only way for accessing private data, e.g.

holiday.theMonth()dayPtr->theDay()

Page 23: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

23

(iv) Assignment:(iv) Assignment:

Instances of the same class can be assigned to each other directly, using the assignment operator (obviously an overloaded operator as we use it for all object types, and they are certainly structurally not the same). Example:Example:Date today, someday;

today = Date(5,6,2000);

someday = today;

day 5month 6year 2000

today

day 5month 6year 2000

someday

literal for the Date class, produced by constructor; similar to 5 for int, or 'a' for char

Page 24: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

24

iv) iv) Constant Member Functions and Constant Objects Constant member functions are functions that do not change the data members of the class. They are defined through the const qualifier after the method declaration e.g.

int theDay() const;int theMonth() const;int theYear() const;

Note that constant member functions can be invoked by non constant data objects, e.g.

today.theDay()However constant objects, that are declared with the const qualifier before the type, can invoke only constant functions, e.g.const Date Christmas99(25, 12, 1999);cout << Christmas99.theMonth()<<","

<<Christmas99.theDay()<<","<<Christmas99.theYear()<<endl;

But Christmas99.advance( ); is illegal!!!is illegal!!!

Page 25: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

25

(vi) (vi) Terminology

• Classes receive messages and reply to them through functions. Sending a message to an object means calling a member function. The object responds through the returned value. (With just a little stretch of the paradigm one can think of the calling environment as the client and the object that returns the information as the server).

• The grouping of information pertinent to a type in one single syntactic construct is known as encapsulation.

• The principle of separating the interface of a class from the details of its implementation, and hiding the latter from the public eye is known as information hiding.

Page 26: 11/03/08MET CS 563 - Fall 2008 7. Structures and Classes 1 7. Implementing Objects with struct and class 7.1. Structures—Implementing Objects with struct

11/03/08 MET CS 563 - Fall 2008 7. Structures and Classes

26

Classes - Summary

• Classes encapsulate object behavior together with object data. They are defined with the class keyword, followed by specifications of their public and private domains.

• The interface of the class is implemented as public member functions or methods, that can be accessed anywhere a class object is in scope.

• Any data and computations that are not part of the interface are implemented as private members (data or utility functions).

• Initialization is done by a special member function, called a constructor, that must have the name of the class and no return type. The constructor is called automatically every time and object is created.

• The default access type for class members is private.

• The default access type of structure members is public.

• Classes can be assigned to each other through the assignment operator the same way as basic data types.