Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 1.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Chapter 6: A First Look at classes. Object-Oriented Programming  Object-oriented programming is centered on creating objects rather than procedures.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Starting Out with C++: Early Objects 5th Edition
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
Review of C++ Programming Part II Sheng-Fang Huang.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
1 Object-Oriented Programming Using C++ CLASS 27.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Starting Out With Java 5 (Control Structures to Objects) Chapter 6 By Tony Gaddis Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Introduction To Classes Chapter Procedural And Object Oriented Programming Procedural programming focuses on the process/actions that occur in a.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Procedural and Object-Oriented Programming 13.1.
1 Chapter 13 Introduction to Classes. 2 Topics 12.1 Procedural and Object-Oriented Programming 12.2 Introduction to Classes 12.3 Defining an Instance.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 7: Introduction.
Chapter 10 Introduction to Classes
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 12 Introduction to Classes.
C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not.
1 CSE 2341 Object Oriented Programming with C++ Note Set #5.
Lecture 19: Introduction to Classes Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 3 A First Look at Classes and Objects.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Starting Out with C++, 3 rd Edition 1 Chapter 13 – Introduction to Classes Procedural and Object-Oriented Programming Procedural programming is a method.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
1 Object-Oriented Programming Using C++ CLASS 2 Honors.
1 Class 19 Chapter 13 – Creating a class definition.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a.
Review: Two Programming Paradigms
Introduction to Classes
Chapter 7: Introduction to Classes and Objects
Introduction to Classes
Classes and Objects.
Lecture 8 Object Oriented Programming (OOP)
Presentation transcript:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 1

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Introduction to Classes 13

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Procedural and Object-Oriented Programming 13.1

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented programming is based on the data and the functions that operate on it. Objects are instances of Abstract Data Types (ADTs) that represent the data and its functions

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Procedural Programming Typically, data is stored in a collection of variables and/or structures, coupled with a set of functions that perform operations on the data The data and the functions are separate entities

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Procedural Programming Example Write a C++ program to calculate the area of a rectangle Variables: Functions: double widthHolds the rectangle’s width double lengthHolds the rectangle’s length double areaHolds the rectangle’s area setData()Stores values in width and length calculateArea(double, double)Calculates the area of the rectangle displayWidth(double)Displays the width of the rectangle diaplayLength(double)Displays the length of the rectangle displayArea(double)Displays the area of the rectangle

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Procedural Programming Example //calculate the area of a ractangle …. void setData(); double calculateArea(double, double); void displayWidth(double); void diaplayLength(double); void displayArea(double); int main() { double width; double length; double area; …… } Data and functions are separate

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Limitations of Procedural Programming If the data structures change, many functions must also be changed data structure: way of storing data in computer, e.g. array, structs etc. Programs that are based on complex function hierarchies are: difficult to understand and maintain functions must be designed with those variables and their data structure in mind difficult to modify and extend easy to break

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Introducing to Classes: Review on C++ Struct Structure: C++ construct that allows multiple variables to be grouped together General Format: struct { type1 field1; type2 field2;... };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Example struct Declaration: struct Student { int studentID; string name; short yearInSchool; double gpa; }; structure tag structure members Student bill; Define a Student Struct Varaible:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide A Complete Program Using C++ Struct

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Program (Continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Questions on Struct Look at the following structure declaration. struct Employee { char name[25]; int idNum; }; In this declaration, Employee is A).a memberC).a tag B).an arrayD).None of these

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Questions on Struct (Cont.) Before a structure variable can be created, the structure must be ________. A) allocated B) declared C) initialized D) all of the above E) none of the above

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Questions on Struct A program includes the following two structure declarations: If package is a variable of a Box structure, which of the following statements will display package's length? A) cout << package.length; B) cout << Box.size.length; C) cout << package.Dimension.length; D) cout << Box.Dimension.length; E) one of the above struct Dimension { int length, width; }; struct Box { char type; string color; Dimension size; };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to Classes 13.2,4,5,6

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object-Oriented Programming Terminology All OOP languages have the following concepts, although the terms they use may differ: classes, object type, factory object instances, objects message passing, method lookup, member function invocation, method binding methods, member function, method function inheritance, subclassing

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object-Oriented Programming Terminology class: like a struct allows bundling of related variables (member data) and the functions that operate on them (member functions) describes the properties that all instances of the class will have it is a new data type you create that is more complex than the basic data types

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object-Oriented Programming Terminology object: like an instance of a struct an object is an instance of a class a class is a category of objects

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Classes and Objects A Class is like a blueprint and objects are like houses built from the blueprint

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object-Oriented Programming Terminology attributes: members of a class methods or behaviors: member functions of a class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide More on Objects data hiding: restricting access to certain members of an object public interface: members of an object that are available outside of the object this allows the object to provide access to some data and functions without sharing its internal details and design provides some protection from data corruption

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Introduction to Classes A class declaration describes the member variables and member functions that its objects will have It is a pattern for creating objects, i.e. Objects are created from a class Format: class ClassName { declaration; };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Declaration Attributes Member functions (e.g., Accessors and Mutators) Access specifiers (e.g., public and private) Constructors/Destructors

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Declaration Example class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Attributes Similar to the members of a C++ struct Also known as data members, or data fields, or class properties For example, the properties of a student may include student ID, name, GPA, address, etc. Attributes class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Member Functions Member functions are functions defined to manipulate class attributes Member Functions class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Defining Member Functions There are two ways to define a member function: One: can place just the function prototype inside the class declaration and write the function definition after the class In the function definition, precede function name with class name and scope resolution operator (::) class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; void Rectangle::setWidth(double w) { width = w;} Declaration Section Implementation Section Note: These two sections should be placed into two different files

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Defining Member Functions There are two ways to define a member function: Two: Can place entire function definition inside the class declaration class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double w) { width = w; } void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; Note: Member functions defined inside the class declaration are called inline functions; Only very short functions, like the one below, should be inline functions; inline function

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Tradeoffs of Inline vs. Regular Member Functions When a regular function is called, control passes to the called function the compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into the program in place of the call larger executable program, but no function call overhead, possibly faster execution

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Separating class declaration, member function definitions, and program that uses the class into separate files is considered good design

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Separating Specification from Implementation Place class declaration in a header file that serves as the class specification file. Name the file ClassName.h, for example, Rectangle.h Place member function definitions in ClassName.cpp, for example, Rectangle.cpp File should #include the class specification file Programs that use the class must #include the class specification file, and be compiled and linked with the member function definitions

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Accessors and Mutators Mutator: a member function that stores a value in a private member variable, or changes its value in some way Accessor: function that retrieves a value from a private member variable. Accessors do not change an object's data, so they should be marked const.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Accessors and Mutators Example class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; Mutators Accessors

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Using const With Member Functions const appearing after the parentheses in a member function declaration specifies that the function will not change any data in the calling object.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Access Specifiers (Public, Private) Used to control access to members of the class public: can be accessed by functions outside of the class private: can only be called by or accessed by functions that are members of the class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Example Private Members Public Members class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide More on Access Specifiers Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Why Have Private Members? Making data members private provides data protection Data can be accessed only through public functions Public functions define the class’s public interface

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Typically in object-oriented technology All the data fields should be private All the methods that are accessible by other should be public

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Constructors 13.7

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Constructors Member function that is automatically called when an object is created Purpose is to construct an object Constructor function name is class name Has no return type

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Continues...

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Contents of Rectangle.ccp Version3 (continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a default constructor for you, one that does nothing. A simple instantiation of a class (with no arguments) calls the default constructor: Rectangle r;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Arguments to Constructors 13.8

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Passing Arguments to Constructors To create a constructor that takes arguments: indicate parameters in prototype: Rectangle(double, double); Use parameters in the definition: Rectangle::Rectangle(double w, double len) { width = w; length = len; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Passing Arguments to Constructors You can pass arguments to the constructor when you create an object: Rectangle r(10, 5);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide More About Default Constructors If all of a constructor's parameters have default arguments, then it is a default constructor. For example: Rectangle(double = 0, double = 0); Creating an object and passing no arguments will cause this constructor to execute: Rectangle r;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Classes with No Default Constructor When all of a class's constructors require arguments, then the class has NO default constructor. When this is the case, you must pass the required arguments to the constructor when creating an object.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overloading Constructors 13.10

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide //class declaration class Student { private: int idNum; string name; double gradePointAverage; public: Student(); Student(int); Student(int, string); Student(int, string, double); …… };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide //implementation section Student::Student() {idNum = 9999; name = “J. Smith”; gradePointAverage = 0.0; } Student::Student(int id) {idNum = id; } …… Student::Student(int id, string nm, double grade) {idNum = id; name = nm; gradePointAverage = grade; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Function Overloading Two or more functions may have the same name, as long as their parameter lists are different.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overloading Constructors A class can have more than one constructor Overloaded constructors in a class must have different parameter lists: Rectangle(); Rectangle(double); Rectangle(double, double);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide From InventoryItem.h (Version 2)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide From InventoryItem.h (Version 2)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide From InventoryItem.h (Version 2)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Member Function Overloading Non-constructor member functions can also be overloaded: void setCost(double); void setCost(char *); Must have unique parameter lists as for constructors

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Destructors 13.9

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Destructors Member function automatically called when an object is destroyed Destructor name is ~ classname, e.g., ~Rectangle Has no return type; takes no arguments Only one destructor per class, i.e., it cannot be overloaded If constructor allocates dynamic memory, destructor should release it

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Contents of InventoryItem.h Version1 (Continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Only One Default Constructor and One Destructor Do not provide more than one default constructor for a class: one that takes no arguments and one that has default arguments for all parameters Square(); Square(int = 0); // will not compile Since a destructor takes no arguments, there can only be one destructor for a class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Constructors, Destructors, and Dynamically Allocated Objects When an object is dynamically allocated with the new operator, its constructor executes: Rectangle *r = new Rectangle(10, 20); When the object is destroyed, its destructor executes: delete r;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Programming Exercise Write a class definition for a Date class that contains three private integer data members: month, day, and year. Create two constructors for the class: one is the default constructor to set the Date as 1/1/2000, another one can take three arguments in to set the three part of the Date. Write mutators and accessors for the three data members. Here are some rules regarding set the three data members: if a month is greater than 12, set it to 12;if a day is greater than 31, then set it to 31. If negative values in, set them to 0. Finally, write a function to display the three data members of Date together. Write a main() function to instantiate a Date object and ask the user to set its month, day and year, then display the Date info to the user.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Defining an Instance of a Class 13.3

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Defining an Instance of a Class An object is an instance of a class Defined like structure variables: Rectangle r; Access members using dot operator: r.setWidth(5.2); cout << r.getWidth(); Compiler error if attempt to access private member using dot operator

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Program 13-1 (Continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Program 13-1 (Continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Program 13-1 (Continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Avoiding Stale Data Some data is the result of a calculation. In the Rectangle class the area of a rectangle is calculated. length x width If we were to use an area variable here in the Rectangle class, its value would be dependent on the length and the width. If we change length or width without updating area, then area would become stale. To avoid stale data, it is best to calculate the value of that data within a member function rather than store it in a variable.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Pointer to an Object Can define a pointer to an object: Rectangle *rPtr; Can access public members via pointer: rPtr = &otherRectangle; rPtr->setLength(12.5); cout getLength() << endl;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Dynamically Allocating an Object We can also use a pointer to dynamically allocate an object.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Private Member Functions 13.11

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Using Private Member Functions A private member function can only be called by another member function It is used for internal processing by the class, not for use outside of the class See the createDescription function in InventoryItem.h (Version 3)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide //class declaration class Student { private: int idNum; string name; double gradePointAverage; void changeGPA(double); public: Student(); void setID(int); void setName(string); void SetGPA(double); …… };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide //using Student class int main() { Student John; …… John.changeGPA(someValue); …… } //implementation section ….. Student::setGPA(double gpa) {changeGPA(gpa); } ERROR

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide An object is ______ A. A category of classes B. A name given to a class C. An instance of a class D. The same as a class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object is to class as ____ A. Library is to book B. Mother is to daughter C. Plato is to philosopher D. President is to Lincoln

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide What type of method/function is used to instantiate/create an object? A. mutator B. selector C. constructor D. accessor

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays of Objects 13.12

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Arrays of Objects Objects can be the elements of an array: InventoryItem inventory[40]; Default constructor for object is used when array is defined

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Arrays of Objects Must use initializer list to invoke constructor that takes arguments: InventoryItem inventory[3] = { "Hammer", "Wrench", "Pliers" };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Arrays of Objects If the constructor requires more than one argument, the initializer must take the form of a function call:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Arrays of Objects It isn't necessary to call the same constructor for each object in an array:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Accessing Objects in an Array Objects in an array are referenced using subscripts Member functions are referenced using dot notation: inventory[2].setUnits(30); cout << inventory[2].getUnits();

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Program 13-3 (Continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide C++ Invariants, Function Preconditions and Postconditions Contract Programming Contract programming is about specifying the design, in terms of the behavior, of your components (functions and classes), and asserting truths about the design of your code in the form of runtime tests placed within it.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide The behavior is specified in terms of function/method preconditions, function/method postconditions, and class invariants. Preconditions state what conditions must be true in order for the function/method to perform according to its design. Postconditions say what conditions will exist after the function/method has performed according to its design.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class invariants state what conditions hold true for the class to be in a state in which it can perform according to its design. Class invariants should be verified after construction, before destruction, and before and after the call of every public member function.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Example char *strcpy (char *dest, char const *src) { char *const r = dest; for(;; ++dest, ++src) { if( ‘\0’ == (*dest = *src)) { break; } return r; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide What are its pre-/post-conditions? Let N be the number of characters pointed to by src that do not contain the null-terminating character ‘\0’ Some preconditions are: src points to a sequence of N + 1 characters (type char) each of whose value is accessible by the expression *(src + n), where n is an integer in the range [0, N + 1) dest points to a block of memory that is writable for a length of N + 1 (or more) characters

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Some postconditions are: For each n in the range [0, N + 1), the expression *(src + n) == *(dest + n) holds true The value returned is the value passed in the dest parameter

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Preconditions char *strcpy(char *dest, char const *src) { char * r; /* Precondition checks */ assert(IsValidReadableString(src)); /* Is src valid? */ assert(IsValidWriteableMemory(dest, 1 + strlen(src))); /* Is dest valid? */ for (r = dest;; ++dest, ++src) { if(‘\0’ == (*dest = *src)) { break; } return r; }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Remarks assert() is the standard C macro that calls abort() if its expression evaluates false (0) IsValidReadableString() is a notional system call that tests to see if a pointer refers to a null-terminated string whose contents span read-accessible memory strlen() is the standard C function that returns the number of characters in a null-terminated string IsValidWriteableMemory() is a notional system call that tests that a pointer refers to a certain size of writeable memory.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Postconditions #if defined(ACMELIB_TEST_POSTCONDITIONS) static char *strcpy_impl(char *dest, char const *src); char *strcpy(char *dest, char const *src) { char *const d = dest; char const *const s = src; char *r; /* Precondition checks */ assert(IsValidReadableString(src)); assert(IsValidWriteableMemory(dest, 1 + strlen(src))); /* Call 'actual' function */ r = strcpy_impl(dest, src);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide /* Postcondition checks. */ assert(0 == strcmp(d, s)); /* Are all contents the same? */ assert(r == d); /* Has it returned the right destination? */ return r; } static char *strcpy_impl(char *dest, char const *src) #else /* ? ACMELIB_TEST_POSTCONDITIONS */ char *strcpy(char *dest, char const *src) #endif /* ACMELIB_TEST_POSTCONDITIONS */ {... // Same impl as shown previously for strcpy() }

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Remarks The reason for the separation into inner and outer functions is that the tests need to be outside the (inner) function context, in order to that the author of the tests can be confident that he/she is seeing the true post- condition This is especially important in C++ where the destructors of local scope objects might affect the post-conditions after their ostensibly ‘’final” test.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Invariants class Dollar { public: Dollar(int dollars, int cents); int getDollars() const; // returns # of dollars int getCents() const; // returns # of cents int getAsCents() const; // returns total amount in cents private: int m_dollars; int m_cents; };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide We can say that the invariant for our Dollar class is that cents must not be more than 99. Hence we might write our invariant in the private member function is_valid(): class Dollar{... private: bool is_valid() const { if( m_cents 99) { return false; } return true; }... };

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Somemethod() { assert(is_valid()); // Verify invariant on method entry //... assert(is_valid()); // Verify invariant on method exit return … }