1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Computer Science 1620 Loops.
Chapter 14: Overloading and Templates
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Pointers OVERVIEW.
CPS120: Introduction to Computer Science Functions.
CSE 332: C++ execution control statements Overview of C++ Execution Control Expressions vs. statements Arithmetic operators and expressions * / % + - Relational.
Pointers, Variables, and Memory. Variables and Pointers When you declare a variable, memory is allocated to store a value. A pointer can be used to hold.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
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.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
11 Introduction to Object Oriented Programming (Continued) Cats.
Object Oriented Programming (OOP) Lecture No. 11.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Classes and Data Structures Jeffrey S. Childs
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Reference parameters (6.2.3) We might need a function to return more than one value Find roots of a quadratic 2 return values. What are they? Get first.
Lecture 7 Pointers & Refrence 1. Background 1.1 Variables and Memory  When you declare a variable, the computer associates the variable name with a particular.
Arithmetic, Class Variables and Class Methods Week 11
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
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.
February 28, 2005 Introduction to Classes. Object Oriented Programming An object is a software bundle of related variables and methods. Software objects.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
11 Introduction to Object Oriented Programming (Continued) Cats.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Fundamental Programming Fundamental Programming Introduction to Functions.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0,
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Pointers. What Is Pointer l every variable has memory address char c=’y’; int i=2; address of variable i is 0022 l address can used to refer to this variable.
User-Written Functions
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.
Motivation and Overview
Classes.
Pointers and Pointer-Based Strings
Student Book An Introduction
Object Oriented Programming COP3330 / CGS5409
Introduction to Classes
Chapter 9 Objects and Classes
Pointers and Pointer-Based Strings
Pointers and dynamic objects
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Threads and concurrency / Safety
Presentation transcript:

1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing: sharing an object/variable among several objects using reference variables and pointers (Tapestry 578 – 583) Static data members in classes (Tapestry 484 – 486, Horton 322 – 325)

2 Overview In this part, you are going to see how different instances of a class ( p1 and p2 below) can share the same variable ( board, below). ChessBoard board; ChessPiece p1, p2; Normally, if we add a variable, board, to the ChessPiece class, there will be a different board for each ChessPiece. Of course, this is not what we want; we want a single board to shared by all ChessPiece objects. There are two solutions for this, one is to use what is called reference variables (this is very easy in term of its use, but slightly more tricky in some other aspects) or to use pointers (this is slightly more complicated to use, but very easy to understand and there are no issues to consider).

Reference Variables It is possible to refer one variable using another name (i.e. creating an alias) using reference variables. Syntax Type & ref_variable_name = existing_variable; int x; int & xr = x; No new memory allocation is done for xr. x and xr refer to the same memory locations after the reference variable declaration. Thus when we say x, it means xr and when we say xr, it is also x. This does not seem very useful now, but will be so when you want to share some data among multiple instances of a class (see shared-unshared toy example). There are some other useful cases as well. –But before that we will see more on reference variables. xxr

Reference Variables The value of reference b cannot be changed after its declaration. –For example, a few lines further, you cannot write: double c = 2.71; &b = c; –expecting now b is c. This is a syntax error (let's see this at refvar.cpp) –Everything is said on the declaration line of b: Reference b and variable a are bound together, not to be ever separated. What about the following addition to the end of code above? Does it change the values a, b, c? double c = 2.71; b = c; –Let's see the answer and another special case on the code (refvar.cpp) a contains: 89 Example (refvar. cpp) double a = ; double &b = a; b = 89; cout << "a contains: " << a << endl; // Displays ?

Reference Variables and Pointers So, are reference variables same as pointers? –Similar concepts but reference variables are NOT pointers. –There are differences. Pointers need to be dereferenced using the * operator to reach the memory location, but reference variables are already dereferenced. int * ptr = new int; * ptr = 10; cout << *ptr; Pointers are more flexible to use. Pointers need not be initialized at declaration (they can be initialized later). Moreover, pointers can be reinitialized to show different locations throughout the program. However, reference variables must be initialized at declaration to an existing variable and cannot refer to another variable later.

Const-Reference Variables Reference variables can be constant, by putting the const keyword before the variable declaration. double x = 4.12; const double & y = x; We already said that binding between reference variable and the existing regular variable cannot change. So, what is constant here? –It is constant such that you cannot change the memory location's value by using the reference variable name. –But this does not mean that this memory location's value cannot change. –We can change it using other references (e.g. using the actual variable name) – see refvar.cpp –We cannot assign a const-reference variable to a normal reference variable double x = 4.12; const double & y = x; y = 3.5; //syntax error, const ref. var. cannot be changed x = 3.5; //legal syntax double & z = y; //syntax error, const-ref. var. cannot be assigned to a regular ref. var.

Reference Parameters: reminder Reference parameters are used to allow a function to modify a calling variable: #include using namespace std; void change (double & r, double s) { r = 30; s = 40; } int main () { double k, m; k = 3; m = 4; change (k, m); cout << k << ", " << m << endl; // Displays ???? return 0; }

Reference Parameters: reminder Reference parameters are used to allow a function to modify a calling variable: #include using namespace std; void change (double & r, double s) { r = 30; s = 40; } int main () { double k, m; k = 3; m = 4; change (k, m); cout << k << ", " << m << endl; // Displays 30, 4 return 0; }

Pointers for sharing If you want to share the same object among various instances of a class object, you must use pointers or reference variables –You should prefer reference variables, if you do the binding at the beginning and do not need to refer to another object during the program. –Pointers are easier, if you feel comfortable on how to manipulate them. One example of need of sharing is that of players (class player) sharing the same game board (class board). We will not follow-up on this example. In the next example that we will see, kids are intended to share the same toy (e.g. same ball that each of them plays with together), but in the naive version, each of them ends up having a separate ball.

(Un)shared Toy– toy class (from Tapestry) Naive version that does not actually work #include using namespace std; // This program demonstrates the use of reference variables and // pointers for sharing among class objects class Toy { public: Toy (const string& name); void Play(); // prints a message void Breaks();// the toy breaks private: string myName;//name of toy bool isWorking;//working condition }; //constructor Toy::Toy(const string & name) : myName(name), isWorking(true) { } See sharetoy.cpp Continued on the next page

// post: toy is played with, message printed void Toy::Play() { if (isWorking) cout << "this " << myName << " is so fun :-)" << endl; else cout << "this " << myName << " is broken :-(" << endl; } void Toy::Breaks() // post: toy is broken { isWorking = false; cout <<endl<< "oops, this " << myName <<" just broke"<<endl<<endl; }

(Un)shared Toy – kid class class Kid { public: Kid (const string & name, Toy & toy); void Play(); private: string myName; //name of the kid Toy myToy; //creates a local copy, this is problematic }; //constructor Kid::Kid(const string & name, Toy & toy) : myName(name), myToy(toy) { }//Equivalent to myToy = toy; void Kid::Play() // post: kid plays and talks about it { cout << "My name is " << myName << ", "; myToy.Play(); }

Does not work as intended int main() { //lets have a !!common!! toy Toy atoy("ball"); Kid erich("erich", atoy); Kid katie("katie", atoy); erich.Play(); katie.Play(); atoy.Breaks(); // the toy is now broken // but this information is not // conveyed to the kids erich.Play(); katie.Play(); //they don’t see that it is broken! return 0; } “erich” “ball” working “katie” “ball” working “ball” working “ball” broken What Happens in Memory: “erich” “ball” working “katie” “ball” working copy After atoy breaks

(Un)shared toy - output Why it did not work out? –Kid class stores a local copy of the Toy object –When we change the state of the source Toy object, it did not effect the Kid class –Basically, Kid did not share a toy, just cloned it.

Solution 1: Reference Variables Similar to reference parameters (alias for memory allocated elsewhere) reference variables refers to memory allocated elsewhere. –making myToy a reference variable avoids creating a copy when myToy is initialized in the Kid initializer list. the Toy object created before the Kid objects are used while constructing the Kid objects –once a reference variable is constructed, it cannot be reassigned to another object a Kid object cannot change toys instance variables that are references must be constructed and initialized in initializer lists, not in the body of class constructors

Sharing with Reference Variables class Kid { public: Kid (const string & name, Toy & toy); void Play(); private: string myName; Toy & myToy; }; //the rest is the same as NAIVE version Kid::Kid(const string & name,Toy & toy) : myName(name), myToy(toy) { }. Same main just works fine! int main() { Toy atoy("ball"); Kid erich("erich", atoy); Kid katie("katie", atoy); erich.Play(); katie.Play(); atoy.Breaks(); erich.Play(); katie.Play(); return 0; }

Sharing with Reference Variables

Sharing with Pointers You can achieve the same result by using a pointer (to a toy object defined outside the class), as shown in the following slides. However, the reference variable makes sharing very simple: –Just add & at the beginning of variable name

Solution 2:Sharing with Pointers class Kid { public: Kid (const string & name, Toy * toy); void Play(); private: string myName; Toy * myToy; }; //constructor Kid::Kid(const string & name, Toy * toy) : myName(name), myToy(toy) { } void Kid::Play() // post: kid plays and talks about it { cout << "My name is " << myName <<", "; myToy->Play(); } “ball” working atoy myToy int main() { Toy atoy("ball"); Kid erich("erich", &atoy); Kid katie("katie", &atoy); erich.Play(); katie.Play(); atoy.Breaks(); erich.Play(); katie.Play(); return 0; }

Sharetoy.cpp (all 3 approaches) Three preprocessor identifiers NAIVE, REFVAR, POINTER are used (at any time only one of them should be defined to run the corresponding approach ) The definiton of class Toy is the same in three approaches. Only Kid class and main are different. These are differentiated using preprocessor directives. Kid Class Definitions: #if defined(NAIVE) // NAIVE version of Kid class comes here... #elif defined(REFVAR) // Reference variable version of Kid class comes here... #elif defined(POINTER) // Pointer version of Kid class comes here... #endif

Sharetoy.cpp (all 3 approaches) Main function: int main() { //lets have a toy Toy atoy("ball"); #if defined(NAIVE) || defined(REFVAR) //Naive and Ref. var. versions are the same Kid erich("erich", atoy); Kid katie("katie", atoy); erich.Play(); katie.Play(); atoy.Breaks(); // the toy is now broken erich.Play(); katie.Play(); #elif defined(POINTER) Kid erich("erich", &atoy); Kid katie("katie", &atoy); erich.Play(); katie.Play(); atoy.Breaks(); // the toy is now broken erich.Play(); katie.Play(); #endif return 0; }

LinkStringSetIterator Class - Revisited Append " seed" to the end of the info field of each node in the list. LinkStringSet c; c.insert("watermellon"); c.insert("apricot"); LinkStringSetIterator itr(c); for (itr.Init(); itr.HasMore(); itr.Next()) { itr.Current().append(" seed"); } cout << "after update\nc : "; Print(c); We have seen that the code on the left works properly when the function Current() return a reference. string & Current() const { return myCurrent->info; } How can we make use reference variables here instead of changing the function return value directly? We may store the return value of Current() in a ref. variable and change it. See next slide after update c : apricot seed watermelon seed size = 2

LinkStringSetIterator Class - Revisited LinkStringSet c; c.insert("watermellon"); c.insert("apricot"); LinkStringSetIterator itr(c); for (itr.Init(); itr.HasMore(); itr.Next()) { string &currentInfo= itr.Current(); currentInfo.append(" seed"); } cout << "after update\nc : "; Print(c); What's output? NOT IN THE BOOKS See linkedstringset.h and.cpp, and linksetdemo.cpp for details after update c : apricot seed watermelon seed size = 2 The definition of Current() is still the same; it return a reference string & Current() const { return myCurrent->info; } The body of the iterator loop changes as shown on the right. Thinking Further: How would you use pointers instead of reference variables?

24 Related: Static Data Member of the Class In certain cases, you can also use a static data member of the class that keeps its value from one construction to the next one. –When a data member is declared as static, only one copy of the data is maintained for all objects of the class. –Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope. You can also use static data members to count the number of instances of a class that you created by calling the constructor. The example below assigns a consecutive ID number to the class instances class User { private: int id; //id of user static int next_id; //common to all instances, but this is not a definition //this is just a prototype-like declaration public: User() //constructs user instances starting from id number 1 { id = next_id; next_id++; //assigns next id to the next instance and then increments } void print () { cout << id << endl; } }; int User::next_id = 1; //this is definition and initialization See static_data_member.cpp