References as Function Arguments

Slides:



Advertisements
Similar presentations
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Advertisements

Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
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 of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
March 6, 2014CS410 – Software Engineering Lecture #10: C++ Basics IV 1 Structure Pointer Operator For accessing members in structures and classes we have.
Operator Overloading Like most languages, C++ supports a set of operators for its built-in types. Example: int x=2+3; // x=5 However, most concepts for.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
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.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Memory Management.
CSE1002 – Problem Solving with Object Oriented Programming
CS410 – Software Engineering Lecture #12: C++ Basics V
Yan Shi CS/SE 2630 Lecture Notes
Overloading C++ supports the concept of overloading Two main types
Motivation for Generic Programming in C++
Constructors and Destructors
Eine By: Avinash Reddy 09/29/2016.
Pointers and Dynamic Arrays
User-Written Functions
Chapter 13: Overloading and Templates
Overloading Operator MySting Example
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Chapter 14 Templates C++ How to Program, 8/e
CS410 – Software Engineering Lecture #11: C++ Basics IV
Pointers and Pointer-Based Strings
Pointers Revisited What is variable address, name, value?
The dirty secrets of objects
Dynamic Memory Review what is static, automatic, dynamic variables? why are dynamic(ally allocated) variables needed what is program stack? function.
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Operator Overloading; String and Array Objects
Advanced Program Design with C++
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
Functions Pass By Value Pass by Reference
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
7 Arrays.
9-10 Classes: A Deeper Look.
Pointers and Pointer-Based Strings
Submitted By : Veenu Saini Lecturer (IT)
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
A Deeper Look at Classes
CS410 – Software Engineering Lecture #8: Advanced C++ III
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
CS 144 Advanced C++ Programming March 21 Class Meeting
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
9-10 Classes: A Deeper Look.
Overloading the << Operator
CS410 – Software Engineering Lecture #6: Advanced C++ I
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
Presentation transcript:

References as Function Arguments void increaseMe(int &x) { x++; } int main() int y = 3; increaseMe(y); cout << y; return 0; Output: 4 C: void increaseMe(int *x) { (*x)++; } int main() int y = 3; increaseMe(&y); printf(“%d”, y); return 0; Output: 4 November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the << Operator Overloading the <<, (), and = operators can be nicely demonstrated with the Matrix example. In order to overload the << operator for printing matrices, we add the following code: class Matrix { public: … friend ostream &operator<<(ostream &out, const Matrix &m); }; (continued on next slide) November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the << Operator ostream &operator<<(ostream &out, const Matrix &m) { out << endl; for (int y = 0; y < m.dy; y++) for (int x = 0; x < m.dx; x++) out << m.p[x][y] << "\t"; } return out; November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the << Operator Now the following main function… int main() { Matrix myMatrix(3, 3); myMatrix.Element(2, 2) = 1; cout << myMatrix << endl; } … prints the following output: 0 0 0 0 0 1 November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the () Operator You may remember that we defined the following member function to access individual elements of a matrix: long &Matrix::Element(int x, int y) { assert(x >= 0 && x < dx && y >= 0 && y < dy); return p[x][y]; } Whenever we want to manipulate an element, we have to explicitly call this function, for example: Matrix myMatrix(3, 3); myMatrix.Element(1, 0) = 3; November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the () Operator It is much more convenient to overload the function call operator for the Matrix class. This will allow us to access Matrix elements by just applying the () operator to a Matrix object. We have to add the following code: class Matrix { public: … long &operator()(int x, int y); // return reference to an element }; (continued on next slide) November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the () Operator long &Matrix::operator()(int x, int y) { assert(x >= 0 && x < dx && y >= 0 && y < dy); return p[x][y]; } This enables us to access elements in the following way: int main() Matrix myMatrix(8, 8); myMatrix(5, 3) = 55; cout << myMatrix(5, 3); November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the = Operator Given the current state of our Matrix class, is the following main() function syntactically correct? int main() { Matrix myMatrix(2, 2), yourMatrix(2, 2), theirMatrix(4, 4); myMatrix(1, 1) = 1; yourMatrix = myMatrix; theirMatrix = myMatrix; myMatrix(0, 0) = 1; cout << myMatrix << yourMatrix << theirMatrix; return 0; } Yes, it is. The compiler provides a default assignment operator that performs copying of all members’ values. However, it acts in a counterintuitive way and also creates memory leaks. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the = Operator What does the output of the program look like? 1 0 0 1 The pointer **p in yourMatrix and theirMatrix is simply copied from myMatrix, that is, it points to the same memory location. Therefore, the three matrices are identical; whenever we change the values of elements in one matrix, we automatically change them in the other two matrices as well. The three matrices are not independent copies. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the = Operator It is important to note that, besides being counterintuitive, this behavior also leads to memory leaks. When the following line of code is being executed… Matrix yourMatrix(2, 2); … memory is being allocated on the heap, and yourMatrix.p points to its location. When we then do the following assignment… yourMatrix = myMatrix; … it implies that yourMatrix.p is set to myMatrix.p, and thus no pointer can access the memory reserved for yourMatrix anymore. The memory remains allocated on the heap but cannot be used or freed anymore, giving us a memory leak. If this occurs in a function that is repeatedly called, the reserved memory will accumulate and eventually interfere with program execution. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the = Operator To avoid this, we have to provide our own assignment operator that also copies the actual elements of a matrix and lets the pointer point to the copied data. We add the following code: class Matrix { public: … Matrix &operator=(const Matrix &m); }; (continued on next slide) November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the = Operator Matrix &Matrix::operator=(const Matrix &m) { if (this != &m) assert(dx == m.dx && dy == m.dy); for (int i = 0; i < dx; i++) for (int j = 0; j < dy; j++) p[i][j] = m.p[i][j]; } return *this; Notice: We only want to allow copying matrices of identical size. Also, if a matrix is to be copied to itself, we do not need to do anything. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Overloading the = Operator Given the new state of our Matrix class with the overloaded = operator, what is the output of the following function? int main() { Matrix myMatrix(2, 2), yourMatrix(2, 2); myMatrix(1, 1) = 1; yourMatrix = myMatrix; myMatrix(0, 0) = 1; cout << myMatrix << yourMatrix; } It is: 1 0 0 1 0 0 November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I The Copy Constructor By the way, a similar problem happens when we pass a class object as a call-by-value argument. Example: void OurFunction(int i, Matrix m); Similar to the default assignment operator, the compiler will provide a default copy constructor. This copy constructor will create a local copy m of the matrix that we pass to the function, and will copy the values of all class members to the members of m. Again, the pointer variables will be copied, but not the memory locations that they point at. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I The Copy Constructor Even worse, once OurFunction(int i, Matrix m) has finished its execution, the local copy Matrix m will automatically be deleted by calling its destructor. However, since m.p points to the location where the data of the matrix in the function call (the matrix external to the function) are stored, the data of that matrix will also be deleted! In other words, calling OurFunction will destroy the matrix that we use as an argument! To solve these problems, we have to provide our own copy constructor. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I The Copy Constructor We add the following code: class Matrix { public: Matrix(const Matrix &m); … } (continued on next slide) November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I The Copy Constructor Matrix::Matrix(const Matrix &m) : dx(m.dx), dy(m.dy) { p = new long*[dx]; // create array of pointers to long integers assert(p != 0); for (int i = 0; i < dx; i++) p[i] = new long[dy]; // for each pointer, create array of l.i.s assert(p[i] != 0); for (int j = 0; j < dy; j++) p[i][j] = m.p[i][j]; } November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates C++ uses the keyword template to provide parametric polymorphism. This allows the same code to be used with respect to various types, where the type is a parameter of the code body. This is a form of generic programming. It allows us to reuse code in a simple and type-safe manner. We will use this technique to define a template for the Matrix class so that we can instantiate matrices for different types of matrix elements. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates template<class TYPE> class Matrix { public: Matrix(int sizeX, int sizeY, TYPE initValue = TYPE()); Matrix(const Matrix &m); ~Matrix(); int GetSizeX() const { return dx; } int GetSizeY() const { return dy; } TYPE &operator()(int x, int y); // return reference to an element Matrix &operator=(const Matrix &m); template<class T> // for friends, separate template declaration necessary friend ostream &operator<<(ostream &out, const Matrix<T> &m); private: TYPE **p; // pointer to a pointer to a TYPE int dx, dy; }; November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates template<class TYPE> Matrix<TYPE>::Matrix(int sizeX, int sizeY, TYPE initValue) : dx(sizeX), dy(sizeY) { assert(sizeX > 0 && sizeY > 0); p = new TYPE*[dx]; // create array of pointers to TYPE assert(p != 0); for (int i = 0; i < dx; i++) p[i] = new TYPE[dy]; // for each pointer, create array of TYPE assert(p[i] != 0); for (int j = 0; j < dy; j++) p[i][j] = initValue; } November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates template<class TYPE> Matrix<TYPE>::Matrix(const Matrix<TYPE> &m) : dx(m.dx), dy(m.dy) { p = new TYPE*[dx]; // create array of pointers to TYPE assert(p != 0); for (int i = 0; i < dx; i++) p[i] = new TYPE[dy]; // for each pointer, create array of TYPE assert(p[i] != 0); for (int j = 0; j < dy; j++) p[i][j] = m.p[i][j]; } November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates template<class TYPE> Matrix<TYPE>::~Matrix() { for (int i = 0; i < dx; i++) delete [] p[i]; // delete arrays of TYPE delete [] p; // delete array of pointers to TYPE } TYPE &Matrix<TYPE>::operator()(int x, int y) assert(x >= 0 && x < dx && y >= 0 && y < dy); return p[x][y]; November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates template<class TYPE> Matrix<TYPE> &Matrix<TYPE>::operator=(const Matrix<TYPE> &m) { if (this != &m) assert(dx == m.dx && dy == m.dy); for (int i = 0; i < dx; i++) for (int j = 0; j < dy; j++) p[i][j] = m.p[i][j]; // memory is already reserved, } // so we just need to copy elements return *this; } November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates template<class TYPE> ostream &operator<<(ostream &out, const Matrix<TYPE> &m) { out << endl; for (int y = 0; y < m.dy; y++) for (int x = 0; x < m.dx; x++) out << m.p[x][y] << "\t"; } return out; November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates int main() { Matrix<char> myMatrix(2, 2, ‘a’); myMatrix(0, 0) = ‘b’; cout << myMatrix << "\n\n"; } Output: b a a a November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates int main() { Matrix<Clock> clockMatrix(4, 4, 620); cout << clockMatrix << "\n\n"; ++clockMatrix(1, 1); clockMatrix(3, 3) = 2*clockMatrix(2, 2); } November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Class Templates Output: 10:20 10:20 10:20 10:20 10:20 10:21 10:20 10:20 10:20 10:20 10:20 20:40 (The code for this example can be found as clock_matrix.C on the course homepage.) November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Function Templates In a similar way, we can use function templates. Here is a function template for copying arrays of different types: template <class TYPE> void copy(TYPE a[], TYPE b[], int n) { for (int i = 0; i < n; i++) a[i] = b[i]; } November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

CS410 – Software Engineering Lecture #15: Advanced C++ I Function Templates Which of the following calls fail to compile? double f1[50], f2[50]; char c1[25], c2[50]; int i1[75], i2[75]; char *ptr1, *ptr2; copy(f1, f2, 50); copy(c1, c2, 10); copy(i1, i2, 40); copy (ptr1, ptr2, 100); copy(i1, f2, 50); copy(ptr1, f2, 50); The last two invocations of copy() fail to compile because their types cannot be matched to the template type. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I

Static Members of Template Classes Static members of template classes are not universal but are specific to each instantiation: template <class T> class Thing { public: static int count; … }; Thing<int> a; Thing<double> b; The static variables Thing<int>::count and Thing<double>::count are distinct. November 1, 2016 CS410 – Software Engineering Lecture #15: Advanced C++ I