Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Slides:



Advertisements
Similar presentations
Class and Objects.
Advertisements

Classes. COMP104 Lecture 25 / Slide 2 Motivation  Types such as int, double, and char are simple objects. * They can only answer one question: “What.
Classes. COMP104 Class / Slide 2 Motivation  Types such as int, double, and char are “stupid” objects. * They can only answer one question: “What value.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Classes and OOP. Basic, built-in, pre-defined types : char, int, double, … Variables + operations on them int a, b,c; c=a+b; c=a mod b; … More complicated,
Computer Programming 1 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 11: Classes and Data Abstraction
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
The switch Statement Selection Revisited. Problem Using OCD, design and implement a program that allows the user to perform an arbitrary temperature conversion.
1 Building Classes (the "++" in C++) (Chapter 14) Representing More Complex Objects.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Practice Building Classes Modeling Objects. Problem Write a program that computes the Dean’s List (full-time students whose GPA 3.0), using a student.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
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.
100 學年度碩士班新生暑期課程 程式設計 Object-Oriented Programming: Part I The Basics of Classes.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Class Operations Creating New Types. Review Last time, we began building, a class to allow us to model temperatures: Last time, we began building Temperature,
Procedural and Object-Oriented Programming
Visit for more Learning Resources
Review What is an object? What is a class?
CS410 – Software Engineering Lecture #11: C++ Basics IV
Templates.
Classes and OOP.
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 9 Introduction To Classes
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Standard Version of Starting Out with C++, 4th Edition
Constructors & Destructors
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Classes Representing Non-Trivial Objects

Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature in both scales.

Preliminary Analysis An object must be directly representable using a single type. A temperature has two attributes: –its magnitude (a double), and –its scale (a character). When an object cannot be directly represented by any of the available types, build a class!

Building Classes Begin by defining variables to store the attributes of the object being represented (a temperature) in a class header file (e.g., Temperature.h): double myMagnitude; char myScale; Pretending that we are the temperature object, we begin the name of each attribute with the prefix, to reinforce this internal perspective. Pretending that we are the temperature object, we begin the name of each attribute with the prefix my, to reinforce this internal perspective.

Building Classes We then wrap these variables in a class declaration: class Temperature { public: private: double myMagnitude; char myScale; }; When declared within a class declaration, such variables are called class data members.

Information Hiding Classes have a public section and a private section. Items declared in the public section are accessible to users of the class; items declared in the private section are inaccessible to users of the class. Data members should go in the private section, to prevent programmers from writing programs that access data members directly.

Why? Software must often be updated. A program that uses a class should still work after the class has been updated. Updating a class may require that its data members be replaced by others. If a program accesses class data members directly, then that program “breaks” if they are replaced. This increases software maintenance costs.

A New Type A programmer can now write: #include “Temperature.h” // class Temperature... Temperature aTemp; and object can be visualized as follows: and object aTemp can be visualized as follows: myMagnitude myScale aTemp The data members and within are uninitialized. The data members myMagnitude and myScale within aTemp are uninitialized.

Operations and Messages Operations on a class object are usually implemented as class function members. A call to a function member: Object.Function() can be thought of as the caller sending the object a message named. can be thought of as the caller sending the object Object a message named Function. The definition of a function member details what does in response to the message. The definition of a function member details what Object does in response to the message.

Example: Output Suppose we want to be able to display the value of a object by sending it the message: Suppose we want to be able to display the value of a Temperature object by sending it the Print() message: aTemp.Print(cout); Using the internal perspective (where I am the object receiving the message): Using the internal perspective (where I am the Temperature object receiving the message):Specification: Receive: out, an ostream. Output: myMagnitude and myScale, via out. Passback: out, containing the new values.

Function Member Definitions void Temperature::Print(ostream & out) const { out << myMagnitude << myScale; } The function returns nothing, so its return-type is. The function returns nothing, so its return-type is void. The full name tells the compiler this is a function member. The full name Temperature::Print() tells the compiler this is a Temperature function member. The caller passes and changes an argument, so we need a reference parameter to store this argument. The caller passes and changes an ostream argument, so we need a reference parameter to store this argument. Function members that change no data members should be defined as function members. Function members that change no data members should be defined as const function members. In Temperature.cpp:

Function Member Prototypes class Temperature { public: void Print(ostream & out) const; private: double myMagnitude; char myScale; }; By declaring the prototype within the class, we tell the compiler that class has a function member named, and that objects should “understand” the message. By declaring the prototype within the class, we tell the compiler that class Temperature has a function member named Print(), and that Temperature objects should “understand” the Print() message. Most function prototypes go in the class public section.

Problem At present, a declaration: At present, a Temperature declaration: Temperature aTemp; leaves ’s data members of uninitialized. leaves aTemp ’s data members of uninitialized. To auto-initialize them to a default value (e.g., ), we can use a special function called a constructor. To auto-initialize them to a default value (e.g., 0C ), we can use a special function called a constructor.

Constructors A constructor function is a class function member whose task is to initialize the class data members. Because they just initialize data members, they don’t return anything, and so their specification is often given as a postcondition (a boolean expression that is true when the function terminates). Default Constructor Specification: Postcondition: myMagnitude == 0.0 && myScale == ‘C’.

Constructor Definition Since it returns nothing, a constructor has no return type (not even ). Since it returns nothing, a constructor has no return type (not even void ). The name of a constructor is always the name of the class (in this case ). The name of a constructor is always the name of the class (in this case Temperature() ). As a function member of class, its full name is. As a function member of class Temperature, its full name is Temperature::Temperature(). Temperature::Temperature() { myMagnitude = 0.0; myScale = ‘C’; }

Constructor Prototype class Temperature { public: Temperature(); void Print(ostream & out) const; private: double myMagnitude; char myScale; }; Since they specify the first thing a user of the class needs to know (i.e., how to define class objects), constructor prototypes are usually the first function members listed in the public section of the class.

Object Definitions A programmer can now write: Temperature aTemp; and object can be visualized as follows: and object aTemp can be visualized as follows: The class constructor is automatically called whenever a class object is defined. C myMagnitude myScale aTemp 0.0

Testing To test this much, we can write: //... documentation //... other #includes #include “Temperature.h” int main() { Temperature aTemp; aTemp.Print(cout); // displays 0C }//ex11-1.cpp

Problem 2 At present, we can only initialize a Temperature to a default value: Temperature aTemp; We have no means of initializing a to any other value. We have no means of initializing a Temperature to any other value. To initialize a to a particular value (e.g., ), we can overload the constructor with a second definition. To initialize a Temperature to a particular value (e.g., 98.6F ), we can overload the constructor with a second definition.

Constructor 2 To overload the constructor, we just provide a second definition (and prototype) that differs from all other constructors in at least one parameter. To initialize the data members of our class, this second constructor must receive the initial values via its parameters. Constructor 2 Specification: Receive: magnitude, a double; scale, a char. Precondition: scale == ‘F’ || scale == ‘C’. Postcondition: myMagnitude == magnitude && myScale == scale. myScale == scale.

Constructor 2 Definition As before, we place this (second) constructor definition in the implementation file -- Temperature.cpp. Temperature::Temperature(double magnitude, char scale) { assert(scale == ‘F’ || scale == ‘C’); myMagnitude = magnitude; myScale = scale; }

Constructor 2 Prototype class Temperature { public: Temperature(); Temperature(double magnitude, char scale); void Print(ostream & out) const; private: double myMagnitude; char myScale; }; The same name can be used to define different functions, provided the signature (the list of the parameter types) of each function is different.

Object Definitions A programmer can now write: Temperature temp1, temp2(98.6, ‘F’); and and are defined as follows: and temp1 and temp2 are defined as follows: The compiler uses the number of arguments in a declaration to decide which constructor to use in initializing an object. C myMagnitude myScale temp1 0.0 F myMagnitude myScale temp2 98.6

Testing To test this much, we can write: //... documentation //... other #includes #include “Temperature.h” int main() { Temperature temp1, temp2(98.6, ‘F’); temp1.Print(cout); // displays 0C cout << endl; temp2.Print(cout); // displays 98.6F }//ex11-2.cpp

Calvin College Input It is useful to be able to input a. It is useful to be able to input a Temperature. From the internal perspective, we can specify this task as follows. Specification: Receive: in, an istream. Precondition: in contains valid magnitude and scale values. Input: the magnitude and scale values from in. Passback: in, minus its magnitude and scale values. Postcondition: myMagnitude == magnitude && myScale == scale. myScale == scale.

Calvin College Input Prototype Unlike output, the input operation changes the class data members, and so is not a function. Unlike output, the input operation changes the class data members, and so is not a const function. class Temperature { public: Temperature(); Temperature(double magnitude, char scale); void Read(istream & in); void Print(ostream & out) const; private: double myMagnitude; char myScale; };

Calvin College Input Definition void Temperature::Read(istream & in) { double magnitude; char scale; in >> magnitude >> scale; if (islower(scale)) scale = toupper(scale); assert(in.good() && scale == ‘C’ || scale == ‘F’); myMagnitude = magnitude; myScale = scale; } Input is an easy place for errors to occur, so always carefully check the preconditions of an input function.

Calvin College Testing To test this function, we can write: //... documentation //... other #includes #include “Temperature.h” int main() { cout << “\nEnter a temperature: “; Temperature temp1; temp1.Read(cin); // read it temp1.Print(cout); // echo it back cout << endl; }//ex11-3.cpp

Calvin College Conversion Functions To find out the celsius equivalent of a class object, we want to be able to send it the Celsius() message. Temperature temp1; //... Temperature temp2 = temp1.Celsius(); From the internal perspective, our specification is: Specification: Return: the Celsius equivalent of myself.

Calvin College Celsius() Prototype This operation will not alter the class data members, and so should be declared a function. This operation will not alter the class data members, and so should be declared a const function. class Temperature { public: Temperature(); Temperature(double magnitude, char scale); Temperature Celsius() const; void Read(istream & in); void Print(ostream & out) const; private: double myMagnitude; char myScale; };

Calvin College Celsius() Definition Temperature Temperature::Celsius() const { switch (myScale) { case ‘C’: return Temperature(myMagnitude, ‘C’); case ‘F’: return Temperature((myMagnitude - 32)/1.8, ‘C’); default: cerr << “\nInvalid scale: “ << myScale << “ in Celsius().\n” << endl; exit(1); }

Calvin College Celsius() Definition Temperature Temperature::Celsius() const { switch (myScale) { case ‘C’: return Temperature(myMagnitude, ‘C’); case ‘F’: return Temperature((myMagnitude - 32)/1.8, ‘C’); default: cerr << “\nInvalid scale: “ << myScale << “ in Celsius().\n” << endl; exit(1); } Using our second constructor, we can build our return-value dynamically! Using our second Temperature constructor, we can build our return-value dynamically!

Calvin College Testing To test this function, we can write: #include “Temperature.h” int main() { cout << “\nEnter a temperature: “; Temperature temp1, temp2; temp1.Read(cin); // read temp2 = temp1.Celsius(); // convert temp2.Print(cout); // output cout << endl; }//ex11-4.cpp

Calvin College Testing Alternatively, we can chain messages: #include “Temperature.h” int main() { cout << “\nEnter a temperature: “; Temperature temp1; temp1.Read(cin); temp1.Celsius().Print(cout); cout << endl; } This sends the message, returning a, to which we send a message. This sends temp1 the Celsius() message, returning a Temperature, to which we send a Print() message.

Calvin College Summary When no existing type is appropriate to represent an object, the C++ class allows a type to be created. Classes have data members (private), and function members (public). In its definition, a function member’s name must be preceded by the name of the class and the scope operator (::). Class constructor functions allow class objects to be initialized to default, or to specified values.