Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
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.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
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.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
Review of C++ Programming Part II Sheng-Fang Huang.
1 Building Classes (the "++" in C++) (Chapter 14) Representing More Complex Objects.
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Case Study - Fractions Timothy Budd Oregon State University.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
CLASSES : A DEEPER LOOK Chapter 9 Part I 1. 2 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition.
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.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
1 CSE 2341 Object Oriented Programming with C++ Note Set #5.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
1 CSC241: Object Oriented Programming Lecture No 03.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
1 CSC241: Object Oriented Programming Lecture No 08.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Friend Functions. Problem u Assuming two Complex objects u How would one add two numbers? W + X Complex operator+(const Complex& w, const Complex& x);
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Chapter 9 Classes: A Deeper Look, Part 1 Seventh Edition C++ How to Program © by Pearson Education, Inc. All Rights Reserved.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Object Lifetimes and Dynamic Objects Lecture-7. Object Lifetimes and Dynamic Objects External (Global) Objects Persistent (in existence) throughout the.
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,
Classes in C++ By: Mr. Jacobs. Objectives  Explore the implications of permitting programmers to define their own data types and then present C++ mechanism.
Pointer to an Object Can define a pointer to an object:
Visit for more Learning Resources
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
A First C++ Class – a Circle
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Review: C++ class represents an ADT
More C++ Classes Systems Programming.
Presentation transcript:

Class Miscellanea Details About Classes

Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //... private members }; Anything that should be accessible to users of the class should be declared in the public section. Anything else should be declared in the private section.

Private Members The private section should contain a class’s data, plus any “utility” function members useful for implementing the class’s function members, but inappropriate for outside users. class Temperature { public: private: int Compare(const Temperature & temp2) const; double myMagnitude; char myScale; };

Object State Each class object has its own copy of each data member. Temperature temp1(212, ‘F’), temp2(100, ‘C’); An object’s data members’ values make up its state. Each object can have a distinct state. F myMagnitude myScale temp1 212 C myMagnitude myScale temp2 100

Class Scope A class member (data or function) can be directly accessed by any class function member or friend. // member inline char Temperature::Scale() const { return myScale; // private access } Class friends are not function members, but are “normal” functions with permission to access the private section. // friend inline istream & operator>>(istream & in, Temperature & temp) { in >> myMagnitude >> myScale; }

Public Members The public section should contain a class’s operations. class Temperature { public: Temperature(); Temperature(double magnitude, char scale); double Magnitude() const; char Scale() const; Temperature Fahrenheit() const; Temperature Celsius() const; Temperature Kelvin() const; friend istream & operator>>(istream & in, Temperature & temp); friend ostream & operator<<(ostream & out, const Temperature & temp); private: //... private members };

Class Interface The public operations (and a few default ones) make up the interface, or way that a program can use the class. #include “Temperature.h” //... Temperature temp1; // declare cin >> temp1; // input double itsMagnitude = temp1.Magnitude(); // read char itsScale = temp1.Scale(); // members Temperature temp2 = temp1.Kelvin(); // convert cout << temp2; // output

Interfaces (Ct’d) With a few exceptions, an operation not in a class’s interface cannot be applied to a class object. if (temp1 == temp2) // error! //... Since operator== is not defined for Temperature objects, the compiler has no means of knowing how they should be compared. Temperature temp1(212, ‘F’), temp2(100, ‘C’); if (temp1 == temp2) // true or false?

Utilities int Temperature::Compare(const Temperature & t2) const { Temperature leftTemp = Kelvin() // me in K Temperature rightTemp = t2.Kelvin(); // t2 in K return left.Magnitude() - right.Magnitude(); } We can always implement such operations ourselves. If we first define a nifty utility function to compare myself with another Temperature object: Compare() returns: –0 if I am equal to t2, –a negative value if I am less-than t2, and –a positive value if I am greater than t2.

Operations bool Temperature::operator==(const Temperature & temp2) { return Compare(temp2) == 0; // true iff I == temp2 } Then we can easily define the relational operators: bool Temperature::operator!=(const Temperature & temp2) { return Compare(temp2) != 0; // true iff I != temp2 } bool Temperature::operator<(const Temperature & temp2) { return Compare(temp2) < 0; // true iff I < temp2 } //...

Assignment For any user-defined class, C++ provides a default assignment operator (operator=). #include “Temperature.h” //... Temperature temp, saveTemp; cin >> temp; saveTemp = temp; // default assignment //... This default operation simply copies the members of the object to the right of the = into the members of the object to the left of the =.

A Problem A program can consist of multiple files. Suppose a programmer (or programming team) unwittingly #includes a class in two different places? When main.h is compiled, an error will be generated, because the declaration of SomeClass will be compiled more than once. class SomeClass { //... }; SomeClass.h #include “SomeClass.h” class AnotherClass { //... }; AnotherClass.h #include “SomeClass.h” #include “AnotherClass.h” int main() { //... }; main.h

An Ugly Solution #ifndef TEMPERATURE #define TEMPERATURE //... #include directives class Temperature { //... details omitted }; //... inline definitions #endif The solution is to use a new directive named and “wrap” the class declaration as follows: The solution is to use a new directive named #ifndef and “wrap” the class declaration as follows: When an directive is processed, if the identifer following it is not defined, compilation proceeds normally. When an #ifndef directive is processed, if the identifer following it is not defined, compilation proceeds normally. But if it is defined, then all subsequent code is skipped until a,, or directive appears. But if it is defined, then all subsequent code is skipped until a #else, #elif, or #endif directive appears.

An Ugly Solution #ifndef TEMPERATURE #define TEMPERATURE //... #include directives class Temperature { //... details omitted }; //... inline definitions #endif The solution is to use a new directive named and “wrap” the class declaration as follows: The solution is to use a new directive named #ifndef and “wrap” the class declaration as follows: So the first time the file is processed, TEMPERATURE is undefined, and execution proceeds as usual. The first thing following the is a directive that defines the identifier TEMPERATURE. The first thing following the #ifndef is a #define directive that defines the identifier TEMPERATURE. The class declaration is then processed normally.

An Ugly Solution #ifndef TEMPERATURE #define TEMPERATURE //... #include directives class Temperature { //... details omitted }; //... inline definitions #endif The solution is to use a new directive named and “wrap” the class declaration as follows: The solution is to use a new directive named #ifndef and “wrap” the class declaration as follows: The second the file is processed, TEMPERATURE is defined, and everything between there and the is skipped. The second the file is processed, TEMPERATURE is defined, and everything between there and the #endif is skipped. While it isn’t elegant, this ensures that the class declaration is processed just once, regardless of what programmers do.

The Bottom Line It is “good form” to always wrap a class declaration this way, using the uppercase name of the class: This will prevent SomeClass (or AnotherClass) from being declared more than once, regardless of what a programmer does. #ifndef SOME_CLASS #define SOME_CLASS class SomeClass { //... }; #endif SomeClass.h #ifndef ANOTHER_CLASS #define ANOTHER_CLASS #include “SomeClass.h” class AnotherClass { //... }; #endif AnotherClass.h #include “SomeClass.h” #include “AnotherClass.h” int main() { //... }; main.h

A Final Detail class Temperature { //... private: double myMagnitude; char myScale; }; The classes we have seen thus far have “normal” data members: Each class object has its own “local” data members: F myMagnitude myScale temp1 212 C myMagnitude myScale temp2 100

Question Suppose we want class Temperature to keep track of how many Temperature objects have been declared? One way to do so is to use a static data member: class Temperature { public: private: double myMagnitude; char myScale; static int tempCounter; }; int Temperature::tempCounter = 0; Static data members must be initialized externally (outside of the constructor), in the manner shown.

Constructors Each constructor can then increment this counter, so that each new will be counted: Each constructor can then increment this counter, so that each new Temperature will be counted: inline Temperature::Temperature() { myMagnitude = 0.0; myScale = ‘C’; tempCounter++; } inline Temperature::Temperature(double magnitude, char scale) { //... validity-checking omitted myMagnitude = magnitude; myScale = scale; tempCounter++; }

Static Members We can then add a function member to display the value of this counter: We can then add a Count() function member to display the value of this counter: inline int Temperature::Count() const { return tempCounter; } Now, the expression: cout << Temperature::Count() << endl; will display the number of objects currently in existence. will display the number of Temperature objects currently in existence. Static members are sometimes called class variables because they belong to the class, not its objects.

Destructors class Temperature { public: //... ~Temperature(); private: //... }; inline Temperature::~Temperature() { tempCounter--; } To remain accurate, our counter must be decremented each time a is destroyed. To remain accurate, our counter must be decremented each time a Temperature is destroyed. To do this, we can add a destructor function, whose name is the name of the class preceded by tilde (~):

Destructor Details An object’s destructor is called at the end of its scope. Like a constructor, a destructor has no return-type. Unlike a constructor, a destructor can have no parameters so it cannot be overloaded with multiple definitions (a class can have only one destructor function). Destructors are only needed when some action is needed (often “cleanup”) at the end of an object’s lifetime, such as ensuring the consistency of a static member, deallocating memory allocated by a constructor, and so on.

Summary Data members can be “normal” or static. –Normal data members are local to each class object. –Static data members are shared by all class objects. Data members should be declared as private. Function members can be declared –private, for utility functions –public, for operations on the class The public operations on a class make up its interface.

Summary (Ct’d) To avoid “redeclaration” errors, “wrap” every class: #ifndef CLASS_NAME #define CLASS_NAME //... #include directives class ClassName { //... details omitted }; //... inline definitions #endif and the class declaration will only be processed once.

Summary (Ct’d) A class destructor is a function member: –that has no return-type (like a constructor) –whose name is the name of the class preceded by a tilde (~) –that is called automatically at the end of an object’s lifetime –that is only needed when some action must be taken at the end of an object’s lifetime.