introduction to classes and objects · objects •forget programming for a while. •think about...

42
1 1 © 2006 Pearson Education, Inc. All rights reserved. Introduction to Classes and Objects 2 © 2006 Pearson Education, Inc. All rights reserved. 3.1 Introduction Programs from Chapter 2 All statements were located in function main Typically Programs will consist of Function main and One or more classes Each containing data members and member functions

Upload: others

Post on 28-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

1

1

© 2006 Pearson Education, Inc. All rights reserved.

Introduction to Classes and

Objects

2

© 2006 Pearson Education, Inc. All rights reserved.

3.1 Introduction

• Programs from Chapter 2– All statements were located in function main

• Typically– Programs will consist of

• Function main and• One or more classes

– Each containing data members and member functions

Page 2: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

2

3

© 2006 Pearson Education, Inc. All rights reserved.

Objects

•Forget programming for a while.•Think about the things in the world that are objects, and things that are not objects.•QUESTION 1:

–List four objects and list four non-objects.

The student ageA student4

The shoe colorA shoe3The car modelA car2The pen typeA pen1

Non-objectsObjects

4

© 2006 Pearson Education, Inc. All rights reserved.

What Makes an Object?

•It is easier to list things that are objects than to list thingsthat are not objects.

•Humans view the world in object oriented terms.

•The human brain wants to think about objects, and our thoughts and memories are organized into objects and their relationships.

•One of the ideas of object-oriented software is to organized software in a way that matches the thinking style of our object-oriented brains.

Page 3: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

3

5

© 2006 Pearson Education, Inc. All rights reserved.

What Makes an Object?

•QUESTION 2:–Look at my list of objects and your own list and try to describewhat all objects have in common.

•Answer:–An object is made of tangible material (the pen is made of plastic, metal, ink). –An object holds together as a single whole (the whole pen). –An object has properties/attributes (the color of the pen, where it is, how thick it writes...). –An object can do things and can have things done to it.

6

© 2006 Pearson Education, Inc. All rights reserved.

Characteristics of Objects

•Bank account is an object–Has existence –Has attributes (the balance, interest rate, owner) –You can do things to it (deposit money, cancel it)–It can do things (charge for transactions, appreciate interest)

•An object has –identity (it acts as a single whole). –attributes (which might change). –behavior (it can do things and can have things done to it).

Page 4: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

4

7

© 2006 Pearson Education, Inc. All rights reserved.

Characteristics of Objects

•QUESTION 3:Consider a tube of four yellow tennis balls–Is the tube of tennis balls an object?

•Yes. It has identity (my tube of balls is different than yours), it has attributes (opened, unopened, brand name, location), and behavior(although not much).

–Is each tennis ball an object? •Yes. It is OK for objects to be part of other objects. Although each ball has nearly the same state and behavior as the others, each has its own identity.

8

© 2006 Pearson Education, Inc. All rights reserved.

Characteristics of Objects

•QUESTION 3:Consider a tube of four yellow tennis balls–Could the top two balls be considered a single object?

•Not ordinarily. Each has its own identity independent of the other. If they were joined together with a stick you might consider them as one object.

–Is the color of the balls an object? •No. It is a property of each ball.

Page 5: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

5

9

© 2006 Pearson Education, Inc. All rights reserved.

Software Objects•Many programs are written to do things that are concerned with the real world.

•It is convenient to have "software objects" that are similar to "real world objects".

•This makes the program and its computation easier to think about.

•Software objects will have identity, attributes, and behavior just as do real world objects.

•Of course, software objects exist entirely within a computer system and don't directly affect real world objects.

•QUESTION 4:–What are software objects made out of?

•Computer memory.

10

© 2006 Pearson Education, Inc. All rights reserved.

Software Objects as Memory•Objects (real world and software) have identity, state, and behavior.

•Software objects have identity.–Each is a distinct chunk of memory. –Just like a yellow tennis ball, each software object is a distinct individual even though it may look nearly the same as other objects.

•Software objects have attributes/data members.–Some of the memory that makes up a software object is used for variables which contain values. –These values are the properties of the object.

•Software objects have behavior.–Some of the memory that makes up a software object contains programs (called member functions/methods) that enable the object to "do things". –The object does something when one of its member functions runs.

Page 6: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

6

11

© 2006 Pearson Education, Inc. All rights reserved.

Picture of an Object

•A software object consists of both–Data members/attributes/variables and –functions/methods

•In the picture, –the yellow bricks represent bytes of memory out of which the object is built.–This object has

•data members/variables, (location, color, size)•member functions/methods (move, resize)

12

© 2006 Pearson Education, Inc. All rights reserved.

Picture of an Object

•The functions must execute in the correct order.

•For an application, the first function to run is the function named main().

•There should be only one method named main() in an application.

•In a small application, main() might do by itself all the computation that needs to be done.

•In a larger application, main() will create objects and use their functions.

Page 7: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

7

13

© 2006 Pearson Education, Inc. All rights reserved.

Class

•To create an object, there needs to be a description of it.

•A class is a description of a kind of object.–It does not by itself create any objects.

•The programmer uses the class to create objects.

•Creating an object is called instantiation.

14

© 2006 Pearson Education, Inc. All rights reserved.

Using a Class to Make Many Objects•A class is like a cookie cutter that can be used many times to make many cookies.

–There is only one cookie cutter, but can be used to make many cookies.

•Cookies are objects and each one has its own individuality because each one is made out of a different section of dough.

•Different cookies may have different characteristics, even though they follow the same basic pattern.

Page 8: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

8

15

© 2006 Pearson Education, Inc. All rights reserved.

Using a Class to Make Many Objects•Cookies may have candy sprinkles or frosting, or may be baked for different lengths of time.

•Cookies can be created. And cookies can be destroyed.

–But destroying cookies does not affect the cookie cutter.–It can be used again if there is dough left.

•A big cookie jar might require many cookies made with many different cookie patterns (stars, hearts, squares).

16

© 2006 Pearson Education, Inc. All rights reserved.

3.4 Defining a Class With a Member Function

• Class definition– Tells compiler what member functions and data members

belong to the class– Keyword class followed by the class’s name– Class body is enclosed in braces ({})

• Specifies data members and member functions• Access-specifier public:

– Indicates that a member function or data member is accessible to other functions and member functions of other classes

Page 9: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

9

17

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_01.cpp

(1 of 1)

1 // Fig. 3.1: fig03_01.cpp

2 // Define class GradeBook with a member function displayMessage;

3 // Create a GradeBook object and call its displayMessage function.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7 8 // GradeBook class definition

9 class GradeBook

10 { 11 public: 12 // function that displays a welcome message to the GradeBook user 13 void displayMessage() 14 { 15 cout << "Welcome to the Grade Book!" << endl; 16 } // end function displayMessage 17 }; // end class GradeBook 18 19 // function main begins program execution 20 int main() 21 { 22 GradeBook myGradeBook; // create a GradeBook object named myGradeBook 23 myGradeBook.displayMessage(); // call object's displayMessage function 24 return 0; // indicate successful termination

25 } // end main

Welcome to the Grade Book!

Beginning of class definition for class GradeBook

Beginning of class body

End of class body

Access specifier public; makes members available to the publicMember function displayMessge

returns nothing

Use dot operator to call GradeBook’s member function

18

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.1

Forgetting the semicolon at the end of a class definition is a syntax error.

Page 10: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

10

19

© 2006 Pearson Education, Inc. All rights reserved.

3.4 Defining a Class With a Member Function (Cont.)

• Member function definition– Return type of a function

• Indicates the type of value returned by the function when it completes its task

• void indicates that the function does not return any value– Function names must be a valid identifier– Parentheses after function name indicate that it is a

function– Function body contains statements that perform the

function’s task• Delimited by braces ({})

20

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.2

Returning a value from a function whose return type has been declared void is a compilation error.

Page 11: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

11

21

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.3

Defining a function inside another function is a syntax error.

22

© 2006 Pearson Education, Inc. All rights reserved.

3.4 Defining a Class With a Member Function (Cont.)

• Using a class– A class is a user-defined type (or programmer-defined

type)• Can be used to create objects

– Dot operator (.)• Used to access an object’s data members and member

functions• Example

– myGradeBook.displayMessage()

• Call member function displayMessage of GradeBook object myGradeBook

Page 12: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

12

23

© 2006 Pearson Education, Inc. All rights reserved.

Fig.3.2 | UML class diagram indicating that class GradeBook has a public displayMessage operation.

24

© 2006 Pearson Education, Inc. All rights reserved.

3.4 Defining a Class With a Member Function (Cont.)

• UML class diagram– A rectangle with three compartments

• Top compartment contains the name of the class• Middle compartment contains the class’s attributes• Bottom compartment contains the class’s operations

– A (+) in front of an operation indicates it is public

Page 13: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

13

25

© 2006 Pearson Education, Inc. All rights reserved.

3.5 Defining a Member Function with a Parameter

• Function parameter(s)– Information needed by a function to perform its task

• Function argument(s)– Values supplied by a function call for each of the function’s

parameters• Argument values are copied into function parameters

26

© 2006 Pearson Education, Inc. All rights reserved.

3.5 Defining a Member Function with a Parameter (Cont.)

• A string– Represents a string of characters– An object of C++ Standard Library class std::string

• Defined in header file <string>

• Library function getline– Used to retrieve input until newline is encountered– Example

• getline( cin, nameOfCourse );

– Inputs a line from standard input into string objectnameOfCourse

Page 14: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

14

27

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_03.cpp

(1 of 2)

1 // Fig. 3.3: fig03_03.cpp

2 // Define class GradeBook with a member function that takes a parameter;

3 // Create a GradeBook object and call its displayMessage function.

4 #include <iostream>

5 using std::cout;

6 using std::cin;

7 using std::endl;

8 9 #include <string> // program uses C++ standard string class

10 using std::string; 11 using std::getline; 12 13 // GradeBook class definition 14 class GradeBook 15 { 16 public: 17 // function that displays a welcome message to the GradeBook user 18 void displayMessage( string courseName ) 19 { 20 cout << "Welcome to the grade book for\n" << courseName << "!" 21 << endl; 22 } // end function displayMessage 23 }; // end class GradeBook 24 25 // function main begins program execution 26 int main() 27 { 28 string nameOfCourse; // string of characters to store the course name 29 GradeBook myGradeBook; // create a GradeBook object named myGradeBook 30

Include string class definition

Member function parameter

Use the function parameter as a variable

28

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_03.cpp

(2 of 2)

31 // prompt for and input course name 32 cout << "Please enter the course name:" << endl; 33 getline( cin, nameOfCourse ); // read a course name with blanks 34 cout << endl; // output a blank line 35 36 // call myGradeBook's displayMessage function 37 // and pass nameOfCourse as an argument 38 myGradeBook.displayMessage( nameOfCourse ); 39 return 0; // indicate successful termination 40 } // end main Please enter the course name: CS101 Introduction to C++ Programming Welcome to the grade book for CS101 Introduction to C++ Programming!

Passing an argument to the member function

Page 15: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

15

29

© 2006 Pearson Education, Inc. All rights reserved.

3.5 Defining a Member Function with a Parameter (Cont.)

• Parameter Lists– Additional information needed by a function– Located in parentheses following the function name– Function may have any number of parameters

• Parameters separated by commas– Number, order and types of arguments in a function call

must match the number, order and types of parameters in the called function’s parameter list

– Modeled in UML• Parameter name, followed by a colon and the parameter type

in the member function’s parentheses

30

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.4

4Placing a semicolon after the right parenthesis enclosing the parameter list of a function definition is a syntax error.

Page 16: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

16

31

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.5

Defining a function parameter again as a local variable in the function is a compilation error.

32

© 2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 3.1

To avoid ambiguity, do not use the same names for the arguments passed to a function and the corresponding parameters in the function definition.

Page 17: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

17

33

© 2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 3.2

Choosing meaningful function names and meaningful parameter names makes programs more readable and helps avoid excessive use of comments.

34

© 2006 Pearson Education, Inc. All rights reserved.

Fig.3.4 | UML class diagram indicating that class GradeBook has a displayMessageoperation with a courseName parameter of UML type String.

Page 18: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

18

35

© 2006 Pearson Education, Inc. All rights reserved.

3.6 Data Members, set Functions and getFunctions

• Local variables– Variables declared in a function definition’s body

• Cannot be used outside of that function body– When a function terminates

• The values of its local variables are lost

• Attributes– Exist throughout the life of the object– Represented as data members

• Variables in a class definition– Each object of class maintains its own copy of attributes

36

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_05.cpp

(1 of 3)

1 // Fig. 3.5: fig03_05.cpp

2 // Define class GradeBook that contains a courseName data member

3 // and member functions to set and get its value;

4 // Create and manipulate a GradeBook object with these functions.

5 #include <iostream>

6 using std::cout;

7 using std::cin;

8 using std::endl;

9 10 #include <string> // program uses C++ standard string class 11 using std::string; 12 using std::getline; 13 14 // GradeBook class definition 15 class GradeBook 16 { 17 public: 18 // function that sets the course name 19 void setCourseName( string name ) 20 { 21 courseName = name; // store the course name in the object 22 } // end function setCourseName 23 24 // function that gets the course name 25 string getCourseName() 26 { 27 return courseName; // return the object's courseName 28 } // end function getCourseName 29

set function modifies private data

get function accesses private data

Page 19: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

19

37

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_05.cpp

(2 of 3)

30 // function that displays a welcome message 31 void displayMessage() 32 { 33 // this statement calls getCourseName to get the 34 // name of the course this GradeBook represents 35 cout << "Welcome to the grade book for\n" << getCourseName() << "!" 36 << endl; 37 } // end function displayMessage 38 private: 39 string courseName; // course name for this GradeBook 40 }; // end class GradeBook 41 42 // function main begins program execution 43 int main() 44 { 45 string nameOfCourse; // string of characters to store the course name 46 GradeBook myGradeBook; // create a GradeBook object named myGradeBook 47 48 // display initial value of courseName 49 cout << "Initial course name is: " << myGradeBook.getCourseName() 50 << endl; 51

Use set and get functions, even within the class

Accessing private data outside class definition

private members accessible only to member functions of the class

38

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_05.cpp

(3 of 3)

52 // prompt for, input and set course name 53 cout << "\nPlease enter the course name:" << endl; 54 getline( cin, nameOfCourse ); // read a course name with blanks 55 myGradeBook.setCourseName( nameOfCourse ); // set the course name 56 57 cout << endl; // outputs a blank line 58 myGradeBook.displayMessage(); // display message with new course name 59 return 0; // indicate successful termination 60 } // end main Initial course name is: Please enter the course name: CS101 Introduction to C++ Programming Welcome to the grade book for CS101 Introduction to C++ Programming!

Modifying private data outside class definition

Page 20: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

20

39

© 2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 3.3

Place a blank line between member-function definitions to enhance program readability.

40

© 2006 Pearson Education, Inc. All rights reserved.

3.6 Data Members, set Functions and getFunctions (Cont.)

• Access-specifier private– Makes a data member or member function accessible only

to member functions of the class– private is the default access for class members– Data hiding

• Returning a value from a function– A function that specifies a return type other than void

• Returns a value to its calling function

Page 21: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

21

41

© 2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 3.1

As a rule of thumb, data members should be declared private and member functions should be declared public. (We will see that it is appropriate to declare certain member functions private, if they are to be accessed only by other member functions of the class.)

42

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.6

An attempt by a function, which is not a member of a particular class to access a private member of that class is a compilation error.

Page 22: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

22

43

© 2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 3.4

Despite the fact that the public and private access specifiers may be repeated and intermixed, list all the public members of a class first in one group and then list all the private mem-bers in another group. This focuses the client’s attention on the class’s public interface, rather than on the class’s implementation.

44

© 2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 3.5

If you choose to list the private members first in a class definition, explicitly use the privateaccess specifier despite the fact that private is assumed by default. This improves pro-gram clarity.

Page 23: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

23

45

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.7

Forgetting to return a value from a function that is supposed to return a value is a compilation error.

46

© 2006 Pearson Education, Inc. All rights reserved.

3.6 Data Members, set Functions and getFunctions (Cont.)

• Software engineering with set and get functions– public member functions that allow clients of a class to

set or get the values of private data members– set functions sometimes called mutators and get functions

sometimes called accessors– Allows the creator of the class to control how clients access private data

– Should also be used by other member functions of the same class

Page 24: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

24

47

© 2006 Pearson Education, Inc. All rights reserved.

3.6 Data Members, set Functions and getFunctions (Cont.)

• UML diagram– Indicating the return type of an operation

• Place a colon and the return type after the parentheses following the operation name

– Minus sign used to indicate private members

48

© 2006 Pearson Education, Inc. All rights reserved.

Fig.3.6 | UML class diagram for class GradeBook with a private courseName attribute and public operations setCourseName, getCourseName and displayMessage.

Page 25: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

25

49

© 2006 Pearson Education, Inc. All rights reserved.

3.7 Initializing Objects with Constructors

• Constructors– Functions used to initialize an object’s data when it is

created• Call made implicitly when object is created • Must be defined with the same name as the class• Cannot return values

– Not even void– Default constructor has no parameters

• The compiler will provide one when a class does not explicitly include a constructor

50

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_07.cpp

(1 of 3)

1 // Fig. 3.7: fig03_07.cpp

2 // Instantiating multiple objects of the GradeBook class and using

3 // the GradeBook constructor to specify the course name

4 // when each GradeBook object is created.

5 #include <iostream>

6 using std::cout;

7 using std::endl;

8 9 #include <string> // program uses C++ standard string class

10 using std::string; 11 12 // GradeBook class definition 13 class GradeBook 14 { 15 public: 16 // constructor initializes courseName with string supplied as argument 17 GradeBook( string name ) 18 { 19 setCourseName( name ); // call set function to initialize courseName 20 } // end GradeBook constructor 21 22 // function to set the course name 23 void setCourseName( string name ) 24 { 25 courseName = name; // store the course name in the object 26 } // end function setCourseName 27

Constructor has same name as class and no return type

Initialize data member

Page 26: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

26

51

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_07.cpp

(2 of 3)

28 // function to get the course name 29 string getCourseName() 30 { 31 return courseName; // return object's courseName 32 } // end function getCourseName 33 34 // display a welcome message to the GradeBook user 35 void displayMessage() 36 { 37 // call getCourseName to get the courseName 38 cout << "Welcome to the grade book for\n" << getCourseName() 39 << "!" << endl; 40 } // end function displayMessage 41 private: 42 string courseName; // course name for this GradeBook 43 }; // end class GradeBook 44

52

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_07.cpp

(3 of 3)

45 // function main begins program execution 46 int main() 47 { 48 // create two GradeBook objects 49 GradeBook gradeBook1( "CS101 Introduction to C++ Programming" ); 50 GradeBook gradeBook2( "CS102 Data Structures in C++" ); 51 52 // display initial value of courseName for each GradeBook 53 cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() 54 << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() 55 << endl; 56 return 0; // indicate successful termination 57 } // end main gradeBook1 created for course: CS101 Introduction to C++ Programming gradeBook2 created for course: CS102 Data Structures in C++

Creating objects implicitly calls the constructor

Page 27: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

27

53

© 2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 3.2

Unless no initialization of your class’s data members is necessary (almost never), provide a constructor to ensure that your class’s data members are initialized with meaningful values when each new object of your class is created.

54

© 2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 3.5

Data members can be initialized in a constructor of the class or their values may be set later after the object is created. However, it is a good software engineering practice to ensure that an object is fully initialized before the client code invokes the object’s member functions. In general, you should not rely on the client code to ensure that an object gets initialized properly.

Page 28: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

28

55

© 2006 Pearson Education, Inc. All rights reserved.

3.7 Initializing Objects with Constructors (Cont.)

• Constructors in a UML class diagram– Appear in third compartment, with operations– To distinguish a constructor from a class’s operations

• UML places the word “constructor” between guillemets before the constructor’s name

– <<constructor>>– Usually placed before other operations

56

© 2006 Pearson Education, Inc. All rights reserved.

Fig.3.8 | UML class diagram indicating that class GradeBook has a constructor with a name parameter of UML type String.

Page 29: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

29

57

© 2006 Pearson Education, Inc. All rights reserved.

3.8 Placing a Class in a Separate File for Reusability•.cpp file is known as a source-code file• Header files

– Separate files in which class definitions are placed• Allow compiler to recognize the classes when used elsewhere

– Generally have .h filename extensions

• Driver files– Program used to test software (such as classes)– Contains a main function so it can be executed

58

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_09.cpp

(1 of 2)

1 // Fig. 3.9: GradeBook.h

10 // GradeBook class definition

11 class GradeBook

12 {

13 public:

14 // constructor initializes courseName

15 GradeBook( string name )

16 {

17 setCourseName( name ); // call set function

18 } // end GradeBook constructor

19

20 // function to set the course name

21 void setCourseName( string name )

22 {

23 courseName = name; // store the course name

24 } // end function setCourseName

25

Class definition is in a header file

Page 30: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

30

59

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_09.cpp

(2 of 2)

26 // function to get the course name

27 string getCourseName()

28 {

29 return courseName;

30 } // end function getCourseName

31

32 // display a welcome message

33 void displayMessage()

34 {

35 // call getCourseName to get the courseName

36 cout << "Welcome for\n" << getCourseName()

37 << "!" << endl;

38 } // end function displayMessage

39 private:

40 string courseName;

41 }; // end class GradeBook

60

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_10.cpp

(1 of 1)

2 // Including GradeBook.h

3 #include <iostream>

4 using std::cout;

5 using std::endl;

7 #include "GradeBook.h"

9 int main()

11 {

12 // create two GradeBook objects

13 GradeBook gb1( "CS101" );

14 GradeBook gb2( "CS102" );

17 cout << gb1.getCourseName()

18 << "\n" << gb2.getCourseName()

19 << endl;

20 return 0;

21 } // end main

Including the header file causes the class definition to be copied into the file

Page 31: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

31

61

© 2006 Pearson Education, Inc. All rights reserved.

3.8 Placing a Class in a Separate File for Reusability (Cont.)

• #include preprocessor directive– Used to include header files

• Instructs C++ preprocessor to replace directive with a copy of the contents of the specified file

– Quotes indicate user-defined header files• Preprocessor first looks in current directory

– If the file is not found, looks in C++ Standard Library directory

– Angle brackets indicate C++ Standard Library• Preprocessor looks only in C++ Standard Library directory

62

© 2006 Pearson Education, Inc. All rights reserved.

3.8 Placing a Class in a Separate File for Reusability (Cont.)

• Creating objects– Compiler must know size of object

• C++ objects typically contain only data members• Compiler creates one copy of class’s member functions

– This copy is shared among all the class’s objects

Page 32: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

32

63

© 2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 3.3

To ensure that the preprocessor can locate header files correctly, #include preprocessor directives should place the names of user-defined header files in quotes (e.g., "GradeBook.h") and place the names of C++ Standard Library header files in angle brackets (e.g., <iostream>).

64

© 2006 Pearson Education, Inc. All rights reserved.

3.9 Separating Interface from Implementation

• Interface– Describes what services a class’s clients can use and how to

request those services• But does not reveal how the class carries out the services• A class definition that lists only member function names,

return types and parameter types– Function prototypes

– A class’s interface consists of the class’s public member functions (services)

• Separating interface from implementation– Client code should not break if implementation changes, as

long as interface stays the same

Page 33: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

33

65

© 2006 Pearson Education, Inc. All rights reserved.

3.9 Separating Interface from Implementation (Cont.)

• Separating interface from implementation (Cont.)– Define member functions outside the class definition, in a

separate source-code file• In source-code file for a class

– Use binary scope resolution operator (::) to tie each member function to the class definition

• Implementation details are hidden– Client code does not need to know the implementation

– In header file for a class• Function prototypes describe the class’s public interface

66

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_11.cpp

(1 of 1)

1 // Fig. 3.11: GradeBook.h

2 // GradeBook class definition. This file presents GradeBook's public

3 // interface without revealing the implementations of GradeBook's member

4 // functions, which are defined in GradeBook.cpp.

5 #include <string> // class GradeBook uses C++ standard string class

6 using std::string;

7 8 // GradeBook class definition

9 class GradeBook

10 { 11 public: 12 GradeBook( string ); // constructor that initializes courseName 13 void setCourseName( string ); // function that sets the course name 14 string getCourseName(); // function that gets the course name 15 void displayMessage(); // function that displays a welcome message 16 private: 17 string courseName; // course name for this GradeBook 18 }; // end class GradeBook

Interface contains data members and member function prototypes

Page 34: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

34

67

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.8

Forgetting the semicolon at the end of a function prototype is a syntax error.

68

© 2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 3.7

Although parameter names in function prototypes are optional (they are ignored by the compiler), many programmers use these names for documentation purposes.

Page 35: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

35

69

© 2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 3.4

Parameter names in a function prototype (which, again, are ignored by the compiler) can be misleading if wrong or confusing names are used. For this reason, many programmers create function prototypes by copying the first line of the corresponding function definitions (when the source code for the functions is available), then appending a semicolon to the end of each prototype.

70

© 2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.9

When defining a class’s member functions outside that class, omitting the class name and binary scope resolution operator (::) preceding the function names causes compilation errors.

Page 36: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

36

71

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_12.cpp

(1 of 2)

1 // Fig. 3.12: GradeBook.cpp

2 // GradeBook member-function definitions. This file contains

3 // implementations of the member functions prototyped in GradeBook.h.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7 8 #include "GradeBook.h" // include definition of class GradeBook

9 10 // constructor initializes courseName with string supplied as argument 11 GradeBook::GradeBook( string name ) 12 { 13 setCourseName( name ); // call set function to initialize courseName 14 } // end GradeBook constructor 15 16 // function to set the course name 17 void GradeBook::setCourseName( string name ) 18 { 19 courseName = name; // store the course name in the object 20 } // end function setCourseName 21

Binary scope resolution operator ties a function to its class

GradeBook implementation is placed in a separate source-code file

Include the header file to access the class name GradeBook

72

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_12.cpp

(2 of 2)

22 // function to get the course name 23 string GradeBook::getCourseName() 24 { 25 return courseName; // return object's courseName 26 } // end function getCourseName 27 28 // display a welcome message to the GradeBook user 29 void GradeBook::displayMessage() 30 { 31 // call getCourseName to get the courseName 32 cout << "Welcome to the grade book for\n" << getCourseName() 33 << "!" << endl; 34 } // end function displayMessage

Page 37: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

37

73

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_13.cpp

(1 of 1)

1 // Fig. 3.13: fig03_13.cpp

2 // GradeBook class demonstration after separating

3 // its interface from its implementation.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7 8 #include "GradeBook.h" // include definition of class GradeBook

9 10 // function main begins program execution 11 int main() 12 { 13 // create two GradeBook objects 14 GradeBook gradeBook1( "CS101 Introduction to C++ Programming" ); 15 GradeBook gradeBook2( "CS102 Data Structures in C++" ); 16 17 // display initial value of courseName for each GradeBook 18 cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() 19 << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() 20 << endl; 21 return 0; // indicate successful termination 22 } // end main gradeBook1 created for course: CS101 Introduction to C++ Programming gradeBook2 created for course: CS102 Data Structures in C++

74

© 2006 Pearson Education, Inc. All rights reserved.

3.9 Separating Interface from Implementation (Cont.)

• The Compilation and Linking Process– Source-code file is compiled to create the class’s object

code (source-code file must #include header file)• Class implementation programmer only needs to provide

header file and object code to client– Client must #include header file in their own code

• So compiler can ensure that the main function creates and manipulates objects of the class correctly

– To create executable application• Object code for client code must be linked with the object

code for the class and the object code for any C++ Standard Library object code used in the application

Page 38: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

38

75

© 2006 Pearson Education, Inc. All rights reserved.

Fig.3.14 | Compilation and linking process that produces an executable application.

76

© 2006 Pearson Education, Inc. All rights reserved.

3.10 Validating Data with setFunctions

• set functions can validate data– Known as validity checking– Keeps object in a consistent state

• The data member contains a valid value– Can return values indicating that attempts were made to

assign invalid data

•string member functions– length returns the number of characters in the string– Substr returns specified substring within the string

Page 39: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

39

77

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_15.cpp

(1 of 1)

1 // Fig. 3.15: GradeBook.h

2 // GradeBook class definition presents the public interface of

3 // the class. Member-function definitions appear in GradeBook.cpp.

4 #include <string> // program uses C++ standard string class

5 using std::string;

6 7 // GradeBook class definition

8 class GradeBook

9 {

10 public: 11 GradeBook( string ); // constructor that initializes a GradeBook object 12 void setCourseName( string ); // function that sets the course name 13 string getCourseName(); // function that gets the course name 14 void displayMessage(); // function that displays a welcome message 15 private: 16 string courseName; // course name for this GradeBook 17 }; // end class GradeBook

78

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_16.cpp

(1 of 2)

1 // Fig. 3.16: GradeBook.cpp

2 // Implementations of the GradeBook member-function definitions.

3 // The setCourseName function performs validation.

4 #include <iostream>

5 using std::cout;

6 using std::endl;

7 8 #include "GradeBook.h" // include definition of class GradeBook

9 10 // constructor initializes courseName with string supplied as argument 11 GradeBook::GradeBook( string name ) 12 { 13 setCourseName( name ); // validate and store courseName 14 } // end GradeBook constructor 15 16 // function that sets the course name; 17 // ensures that the course name has at most 25 characters 18 void GradeBook::setCourseName( string name ) 19 { 20 if ( name.length() <= 25 ) // if name has 25 or fewer characters 21 courseName = name; // store the course name in the object 22

set functions perform validity checking to keep courseName in a consistent state

Constructor calls set function to perform validity checking

Page 40: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

40

79

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_16.cpp

(2 of 2)

23 if ( name.length() > 25 ) // if name has more than 25 characters 24 { 25 // set courseName to first 25 characters of parameter name 26 courseName = name.substr( 0, 25 ); // start at 0, length of 25 27 28 cout << "Name \"" << name << "\" exceeds maximum length (25).\n" 29 << "Limiting courseName to first 25 characters.\n" << endl; 30 } // end if 31 } // end function setCourseName 32 33 // function to get the course name 34 string GradeBook::getCourseName() 35 { 36 return courseName; // return object's courseName 37 } // end function getCourseName 38 39 // display a welcome message to the GradeBook user 40 void GradeBook::displayMessage() 41 { 42 // call getCourseName to get the courseName 43 cout << "Welcome to the grade book for\n" << getCourseName() 44 << "!" << endl; 45 } // end function displayMessage

80

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_17.cpp

(1 of 2)

1 // Fig. 3.17: fig03_17.cpp

2 // Create and manipulate a GradeBook object; illustrate validation.

3 #include <iostream>

4 using std::cout;

5 using std::endl;

6 7 #include "GradeBook.h" // include definition of class GradeBook

8 9 // function main begins program execution

10 int main() 11 { 12 // create two GradeBook objects; 13 // initial course name of gradeBook1 is too long 14 GradeBook gradeBook1( "CS101 Introduction to Programming in C++" ); 15 GradeBook gradeBook2( "CS102 C++ Data Structures" ); 16

Constructor will call set function to perform validity checking

Page 41: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

41

81

© 2006 Pearson Education, Inc. All rights reserved.

Outline

fig03_17.cpp

(2 of 2)

17 // display each GradeBook's courseName 18 cout << "gradeBook1's initial course name is: " 19 << gradeBook1.getCourseName() 20 << "\ngradeBook2's initial course name is: " 21 << gradeBook2.getCourseName() << endl; 22 23 // modify myGradeBook's courseName (with a valid-length string) 24 gradeBook1.setCourseName( "CS101 C++ Programming" ); 25 26 // display each GradeBook's courseName 27 cout << "\ngradeBook1's course name is: " 28 << gradeBook1.getCourseName() 29 << "\ngradeBook2's course name is: " 30 << gradeBook2.getCourseName() << endl; 31 return 0; // indicate successful termination 32 } // end main Name "CS101 Introduction to Programming in C++" exceeds maximum length (25). Limiting courseName to first 25 characters.

gradeBook1's initial course name is: CS101 Introduction to Pro gradeBook2's initial course name is: CS102 C++ Data Structures

gradeBook1's course name is: CS101 C++ Programming gradeBook2's course name is: CS102 C++ Data Structures

Call set function to perform validity checking

82

© 2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 3.6

Making data members private and controlling access, especially write access, to those data members through public member functions helps ensure data integrity.

Page 42: Introduction to Classes and Objects · Objects •Forget programming for a while. •Think about the things in the world that are objects, and things that are not objects. •QUESTION

42

83

© 2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 3.5

The benefits of data integrity are not automatic simply because data members are made private—the programmer must provide appropriate validity checking and report the errors.

84

© 2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 3.7

Member functions that set the values of privatedata should verify that the intended new values are proper; if they are not, the set functions should place the private data members into an appropriate state.