2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline...

32
2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data Members Defining a class with a member function Defining a member function with a parameter Data members, set and get functions Initializing objects with Constructors Placing a class in a separate file for reusability Separating interface from implementation

Transcript of 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline...

2003 Prentice Hall, Inc. All rights reserved.

1

Introduction to Classes and Objects

Outline

Introduction

Classes, Objects, Member Functions and Data Members

Defining a class with a member function

Defining a member function with a parameter

Data members, set and get functions

Initializing objects with Constructors

Placing a class in a separate file for reusability

Separating interface from implementation

2003 Prentice Hall, Inc. All rights reserved.

2

Introduction

• previous chapter: all executable statements were located in function main

# include <filename> // preprocessor directivesusing std::cout;…int main(){

// variable declarations……;// statements……;return 0;

}

Typically, any C++ program consists of a function main and one or more classes

Each class contains data members and member functions

2003 Prentice Hall, Inc. All rights reserved.

3

Introduction

• Object-oriented programming (OOP) – Encapsulates data (attributes) and functions

(behavior) into packages called classes

• Information hiding – Class objects communicate across well-defined

interfaces– Implementation details hidden within classes

themselves

• User-defined (programmer-defined) types: classes– Data (data members) – Functions (member functions or methods defined for

classes)– Similar to blueprints – reusable– Class instance: object

2003 Prentice Hall, Inc. All rights reserved.

4

Classes, Objects, Member Functions and Data Members

• Classes (e.g., engineering drawing for a car)– Model objects (e.g., cars)

• Attributes (data members, e.g., car’s color, nb. of doors, etc.)

• Behaviors (member functions)– Defined using keyword class– Member functions

• Methods (e.g., accelerating the car, slowing down, etc.)• Invoked in response to messages and perform

corresponding tasks (when you press the accelerator pedal, car accelerates)

– Note: you as a user/driver, are not concerned of the complex mechanism that actually makes the car goes faster

• Accelerator pedal is the interface you use

2003 Prentice Hall, Inc. All rights reserved.

5

Classes, Objects, Member Functions and Data Members

• An object:– must be created (from a class) before a

program can perform the tasks the class describes (therefore the name OOP).

• E.g., you cannot drive an engineering drawing of a car (i.e., class), you can however drive a car (the object)

– Many objects can be built from one class• e.g.: many cars (objects) can be created from the

same engineering drawing (class)!

• Member access specifiers– public:

• Accessible wherever object of class in scope– private:

• Accessible only to member functions of class

2003 Prentice Hall, Inc. All rights reserved.

6

Classes, Objects, Member Functions and Data Members

• e.g., a class represents a bank account– Member function to deposit money– Member function to withdraw money– Member function to view balance

• Many objects (accounts) can be created from the class bank account

• Every object maintains its own attributes– Attributes are specified by the class’s data

members– Example: each bank account object knows the

balance in the account it represents, and not the balances of other accounts in the bank

2003 Prentice Hall, Inc. All rights reserved.

7

Defining a class with a member function

Class GradeBook (a grade book used by instructor) that maintains student test scores

define a classdefine member functioncreate an object

1 // Fig. 3.1: fig03_01.cpp2 // 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::cin; 78 // GradeBook Class definition9 class GradeBook10 {11 public:12 // Function that displays a welcome message to the GradeBook user13 void displayMessage()14 { 15 cout << “Welcome to the Grade Book!" <<endl; 16 } // end function displayMessage17 }; // end class GradeBook 1819 // function main begins program execution20 int main()21 {22 GradeBook myGradeBook; // create a GradeBook object named myGradeBook23 myGradeBook.displayMessage(); // call object’s displayMessage function 24 return 0; // indicate that program ended successfully 25 } // end main

2003 Prentice Hall, Inc. All rights reserved.

8

Defining a member function with a parameter

• A member function may require one or more parameters that represent additional data it needs to perform its task– example: class BankAccount

• depositAmount member function may require the amount of money to be deposited to be passed by the calling function.

2003 Prentice Hall, Inc. All rights reserved.

9

Defining a member function with a parameter

1 // Fig. 3.3: fig03_03.cpp2 // 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;89 #include <string> // C++ standard string class10 using std::string; 11 using std::getline; 1213 // GradeBook Class definition14 Class GradeBook15 {16 public:17 // Function that displays a welcome message to the GradeBook user18 void displayMessage(string courseName)19 { 20 cout << “Welcome to the Grade Book for\n"<< courseName << "!“ 21 << endl; 22 } // end function displayMessage23 }; // end class GradeBook 24

2003 Prentice Hall, Inc. All rights reserved.

10

Defining a member function with a parameter

25 // function main begins program execution26 int main()27 {28 string nameOfCourse; // string of characters to store the course name29 GradeBook myGradeBook; // create a GradeBook object named myGradeBook3031 // prompt the user to input course name32 cout << “Please enter the course name:"<< endl;33 getline (cin, nameOfCourse); // read a course name with blanks34 cout << endl; // output a blank line 3536 // call myGradeBook’s displayMessage function 37 // and pass nameOfCourse as an argument 38 myGradeBook.displayMessage(nameOfCourse); 39 return 0; // indicate that program ended successfully 40 } // end main

Please enter the course name:

MECH215 Introduction to C++ Programming

Welcome to the grade book for

MECH215 Introduction to C++ Programming!

2003 Prentice Hall, Inc. All rights reserved.

11

Functions with more arguments and parameters

• A function typically has a parameter list to indicate that it takes additional information to execute its task.

• The parameter list may contain any number of parameters, including none at all.

• Each parameter should specify a “type” (e.g., string) and an “identifier” (e.g., courseName).

• A calling function passes these parameters to a called function.

• Multiple parameters in the function parameter list should be separated by a comma.

• The number and order of arguments in a “function call” must match those of the called function.

• More about functions in subsequent chapters!

2003 Prentice Hall, Inc. All rights reserved.

12

Data members, set and get functions

• Local variables: – Declared in the function’s body– Can only be used in the function itself and cannot be

accessed outside the function– When a function terminates, the values of its local

variables are lost

• Note, the attributes of an object of a particular class exist throughout the life of the object– These attributes (or data members) are represented

as variables in a class definition – They are declared in the class body but outside the

body of member function definitions– Each object maintains its own copy of its attributes in

the memory • (remember two accounts (objects) have different

balances)

2003 Prentice Hall, Inc. All rights reserved.

13

Data members, set and get functions1 // Fig. 3.5: fig03_05.cpp2 // define class GradeBook that contains a courseName data member3 // and member function to get and set 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;910 #include <string> // C++ standard string class11 using std::string; 12 using std::getline; 1314 // GradeBook Class definition15 Class GradeBook16 {17 public:18 // Function that sets the course name19 void setCourseName(string name)20 { 21 courseName = name; // store the course name in the object22 } // end function setCourseName23

2003 Prentice Hall, Inc. All rights reserved.

14

Data members, set and get functions24 // Function that gets the course name25 string getCourseName()26 { 27 return courseName; // store the object’s course name28 } // end function getCourseName2930 // Function that displays a welcome message31 void displayMessage()32 { 33 // this statement calls getCourseName to get the34 // name of the course this GradeBook represents. 35 cout << “Welcome to the grade book for\n"<< getCourseName()<<"!“ 36 <<endl;37 } // end function displayMessage38 private:39 string courseName; // course name of this GradeBook 40 }; // end class GradeBook41

2003 Prentice Hall, Inc. All rights reserved.

15

Data members, set and get functions42 // function main begins program execution43 int main()44 {45 string nameOfCourse; // string of characters to store the course name46 GradeBook myGradeBook; // create a GradeBook object named myGradeBook4748 // display initial value of courseName49 cout << “Initial course name is: "<< myGradeBook.getCourseName() 50 << endl;5152 // prompt for input and set course name53 cout << “\nPlease enter the course name:"<< endl;54 getline (cin, nameOfCourse); // read a course name with blanks55 myGradeBook.setCourseName(nameOfCourse); // set the course name5657 cout<< endl; // output a blank line 58 myGradeBook.displayMessage(); // display message with new course name59 return 0; // indicate that program ended successfully 60 } // end main

2003 Prentice Hall, Inc. All rights reserved.

16

Data members, set and get functions

Initial course name is:

Please enter the course name:MECH215 Introduction to C++ Programming

Welcome to the grade book forMECH215 Introduction to C++ Programming!

2003 Prentice Hall, Inc. All rights reserved.

17

Initializing Objects with Constructors

• When an object is created, its data members (e.g., courseName) are by default initialized to empty.

• Constructors can be used to initialize an object when it is created

• A constructor is a special member function that is defined with the same name as a class– The compiler knows how to distinguish a constructor form other

class member functions– A constructor does not return any value, so a return type cannot

be specified (not even void)– Constructor are usually defined as public– Default constructor are provided when no one is specified (a

default constructor does not take any parameters)

• C++ requires a constructor call for each created object– Hence, each object is initialized properly before it is used– The constructor call occurs implicitly when the object is created

2003 Prentice Hall, Inc. All rights reserved.

18

Initializing Objects with Constructors1 // Fig. 3.7: fig03_07.cpp2 // Instantiating multiple objects of the GradeBook class and using3 // the GradeBook constructor to specify the course name when each4 // GradeBook object is created.5 #include <iostream>6 using std::cout; 7 using std::endl; 89 #include <string> // C++ standard string class10 using std::string; 1112 // GradeBook Class definition13 Class GradeBook14 {15 public:16 // constructor initializes courseName with string supplied as argument 17 GradeBook(string name)18 { 19 setCourseName(name); // call set function to initialize courseName20 } // end GradeBook constructor21

2003 Prentice Hall, Inc. All rights reserved.

19

Initializing Objects with Constructors22 // Function that sets the course name23 void setCourseName(string name)24 { 25 courseName = name; // store the course name in the object26 } // end function setCourseName2728 // Function that gets the course name29 string getCourseName()30 { 31 return courseName; // store the object’s course name32 } // end function getCourseName3334 // Function that displays a welcome message35 void displayMessage()36 { 37 // call getCourseName to get the courseName38 cout << “Welcome to the grade book for\n"<< getCourseName()<<"!“ 39 <<endl;40 } // end function displayMessage41 private:42 string courseName; // course name of this GradeBook 43 }; // end class GradeBook44

2003 Prentice Hall, Inc. All rights reserved.

20

Initializing Objects with Constructors45 // function main begins program execution46 int main()47 {48 // create two GradeBook objects49 GradeBook gradeBook1("Mech215 Introduction to C++ Programming"); 50 GradeBook gradeBook2("Mech216 Advanced Programming"); 5152 // display initial value of courseName for each GradeBook object53 cout << "gradeBook1 created for course: "<< gradeBook1.getCourseName() 54 << "\ngradeBook2 created for course: "<< gradeBook2.getCourseName()

55 << endl;56 return 0; // indicate that program ended successfully 57 } // end main

gradeBook1 created for course: MECH215 Introduction to C++ ProgramminggradeBook2 created for course: MECH216 Advanced Programming

2003 Prentice Hall, Inc. All rights reserved.

21

Placing a Class in a Separate File for Reusability

• Class reusability– e.g., C++ standard library type “string” can be used

in any program by including the header <string> in the program

– Class GradeBook from the previous example cannot be reused because the file we defined earlier cannot simply be included in another file since it contains a main function.

• Every program contains only one main function• Files with more than one main function will result in a

compile error• Placing a main in the same file with a class

definition prevents that class from being reused by other programs

– When building an OO C++ program, classes are best defined in “.h” (header file) filename extension to be reusable

2003 Prentice Hall, Inc. All rights reserved.

22

Placing a Class in a Separate File for Reusability

• Class reusability– Programs generally use #include preprocessor

directives to include header files and take advantage of reusable software components (e.g., type string) as well as user defined classes (e.g., GradeBook).

– A program can be separated into two files: filename.h and filename.cpp

• main function is defined in the filename.cpp• Classes are defined in the filename.h • filename.h does not execute by itself because it

does not contain a main function.

2003 Prentice Hall, Inc. All rights reserved.

23

Placing a Class in a Separate File for Reusability

1 // Fig. 3.9: GradeBook.h2 // GradeBook class definition in a separate file from main3 #include <iostream>4 using std::cout; 5 using std::endl; 67 #include <string> // C++ standard string class8 using std::string; 910 // GradeBook Class definition11 Class GradeBook12 {13 public:14 // constructor initializes courseName with string supplied as argument 15 GradeBook(string name)16 { 17 setCourseName(name); // call set function to initialize courseName18 } // end GradeBook constructor1920 // Function that sets the course name21 void setCourseName(string name)22 { 23 courseName = name; // store the course name in the object24 } // end function setCourseName25

2003 Prentice Hall, Inc. All rights reserved.

24

Placing a Class in a Separate File for Reusability

26 // Function that gets the course name27 string getCourseName()28 { 29 return courseName; // store the object’s course name30 } // end function getCourseName3132 // Function that displays a welcome message33 void displayMessage()34 { 35 // call getCourseName to get the courseName36 cout << “Welcome to the grade book for\n"<< getCourseName()<<"!“ 37 <<endl;38 } // end function displayMessage39 private:40 string courseName; // course name of this GradeBook 41 }; // end class GradeBook

2003 Prentice Hall, Inc. All rights reserved.

25

Placing a Class in a Separate File for Reusability

• Fundamental data types (e.g., int, double, etc.) are known to the compiler; however– GradeBook when used in the main program, the

compiler does not know its definition because it is user-defined type

– The compiler does not even know the classes defined in the standard library

• e.g., we must include <string> header file so that the compiler knows the type string when used in the program.

– This enable the compiler to determine the amount of memory that it must reserve for each object of the class

– Ensures that the program calls the member functions of the class correctly

2003 Prentice Hall, Inc. All rights reserved.

26

Placing a Class in a Separate File for Reusability

• When we create two (or more) objects of the same class: – C++ compiler creates only one copy of class

member functions and share them among all objects– Each object needs its own copy of data members

because their contents vary among different objects• e.g.: two (objects) different bank accounts (of bank

account class) with different balance data members.• Member functions (such as deposit, withdraw, etc.) can

be shared among multiple objects.

– The size of memory allocated for an object depends on the class data members

• Including filename.h in the program gives the compiler access to the information it needs in order to allocate memory

2003 Prentice Hall, Inc. All rights reserved.

27

Placing a Class in a Separate File for Reusability

1 // Fig. 3.10: fig03_10.cpp2 // Including class GradeBook from file GradeBook.h for use in main3 #include <iostream>4 using std::cout; 5 using std::endl; 67 #include “GradeBook.h” // include definition of class GradeBook89 // function main begins program execution10 int main()11 {12 // create two GradeBook objects13 GradeBook gradeBook1("Mech215 Introduction to C++ Programming"); 14 GradeBook gradeBook2("Mech216 Advanced Programming"); 1516 // display initial value of courseName for each GradeBook object17 cout << "gradeBook1 created for course: "<< gradeBook1.getCourseName() 18 << "\ngradeBook2 created for course: "<< gradeBook2.getCourseName()

19 << endl;20 return 0; // indicate that program ended successfully 21 } // end maingradeBook1 created for course: MECH215 Introduction to C++ ProgramminggradeBook2 created for course: MECH216 Advanced Programming

2003 Prentice Hall, Inc. All rights reserved.

28

Separating Interface from Implementation

• The interface of a class– Describes what services a class’s clients can use– Describes how to request those services– Does not describe how the class carries out

those services

• Separating Interface from Implementation– Before, all member functions and data members

were all defined within the body of the class definition

– It is better to define member functions outside the class definition

• implementation details are hidden from the client code

2003 Prentice Hall, Inc. All rights reserved.

29

Separating Interface from Implementation

1 // Fig. 3.11: GradeBook.h2 // GradeBook class definition. This file represents GradeBook’s public3 // interface without revealing the implementations of GradeBook’s member 4 // functions, which are defined in GradeBook.cpp5 #include <string>6 using std::string; 78 // GradeBook Class definition9 Class GradeBook10 {11 public:12 GradeBook(string); // constructor initializes courseName 13 void setCourseName(string); // Function that sets the course name14 string getCourseName(); // Function that gets the course name15 void displayMessage(); // Function that displays a welcome message16 private:17 string courseName; // course name of this GradeBook 18 }; // end class GradeBook

2003 Prentice Hall, Inc. All rights reserved.

30

Separating Interface from Implementation

1 // Fig. 3.12: GradeBook.cpp2 // GradeBook member function definitions. This file contains3 // implementations of the member functions prototyped in GradeBook.h.4 #include <iostream>5 using std::cout; 6 using std::endl; 78 #include “GradeBook.h” // include definition of class GradeBook910 // constructor initializes courseName with string supplied as argument 11 GradeBook::GradeBook(string name)12 { 13 setCourseName(name); // call set function to initialize courseName14 } // end GradeBook constructor1516 // Function that sets the course name17 void GradeBook::setCourseName(string name)18 { 19 courseName = name; // store the course name in the object20 } // end function setCourseName21

2003 Prentice Hall, Inc. All rights reserved.

31

Separating Interface from Implementation

22 // Function that gets the course name23 String GradeBook::getCourseName()24 { 25 return courseName; // store the object’s course name26 } // end function getCourseName2728 // Function that displays a welcome message29 void GradeBook::displayMessage()30 { 31 // call getCourseName to get the courseName32 cout << “Welcome to the grade book for\n"<< getCourseName()<<"!“ 33 <<endl;34 } // end function displayMessage

2003 Prentice Hall, Inc. All rights reserved.

32

Separating Interface from Implementation

1 // Fig. 3.13: fig03_13.cpp2 // GradeBook class demonstration after separating3 // its interface from its implementation4 #include <iostream>5 using std::cout; 6 using std::endl; 78 #include “GradeBook.h” // include definition of class GradeBook910 // function main begins program execution11 int main()12 {13 // create two GradeBook objects14 GradeBook gradeBook1("Mech215 Introduction to C++ Programming"); 15 GradeBook gradeBook2("Mech216 Advanced Programming"); 1617 // display initial value of courseName for each GradeBook object18 cout << "gradeBook1 created for course: "<< gradeBook1.getCourseName() 19 << "\ngradeBook2 created for course: "<< gradeBook2.getCourseName()

20 << endl;21 return 0; // indicate that program ended successfully 22 } // end main

gradeBook1 created for course: MECH215 Introduction to C++ ProgramminggradeBook2 created for course: MECH216 Advanced Programming