1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0,

Slides:



Advertisements
Similar presentations
CMSC 202, Version 2/02 1 Operator Overloading Strong Suggestion: Go over the Array class example in Section 8.8 of your text. (You may ignore the Array.
Advertisements

1 Classes Object-oriented programming: Model the problem as a collection of objects that have certain attributes and interact with one another and/or the.
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.
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
1 Lab Session-XII CSIT121 Fall 2000 b Namespaces b Will This Program Compile ? b Master of Deceit b Lab Exercise 12-A b First Taste of Classes b Lab Exercise.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Plab – Exercise 5 C++: references, operator overloading, friends.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Operator Overloading 1. Introduction Let’s define a class for Complex numbers: class Complex { private: double real, image; public: Complex () : real(0.0),
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Abstract Data Types Using Classes Lecture-5. Abstract Data Types Using Classes Representing abstract data types using C++ We need the following C++ keywords.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
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.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
11 Introduction to Object Oriented Programming (Continued) Cats.
Object Oriented Programming (OOP) Lecture No. 11.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
#include guards Practical session #2 Software Engineering
CS 11 C++ track: lecture 3 Today const and const -correctness operator overloading.
1 Lecture 3 More about C++. 2 Topic for today More about classMore about class –Init list –Inline functions –Const –Default function parameters –Static.
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.
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?
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Intoduction to C++ CENG 213 Data Structures1. 2 Programming in C++ C++ –Improves on many of C's features –Has object-oriented capabilities Increases software.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
EC-111 Algorithms & Computing Lecture #6 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Introduction to C++ CENG 213 Data Structures 1.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
C++ Programming Lecture 12 Functions – Part IV
Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading.
C++ Functions A bit of review (things we’ve covered so far)
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
1 Ugly Realities The Dark Side of C++ Chapter 12.
LECTURE 3 PASS BY REFERENCE. METHODS OF PASSING There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference, 
C++ : Operator overloading example
CENG 707 Data Structures and Algorithms
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?
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
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?
Hank Childs, University of Oregon
Initialization List.
Arrays Kingdom of Saudi Arabia
Functions Pass By Value Pass by Reference
CENG 213 Data Structures and Algorithms
Today’s Topic Const Ref:
Variables have attributes
Arrays Arrays A few types Structures of related data items
Object Oriented Programming (OOP) Lecture No. 11
Initialization List.
Presentation transcript:

1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0, float y = 0) : re(x), im(y) { } Complex operator*(Complex rhs) const; float modulus() const; void print() const; }; #endif Complex class Interface in the file Complex.h

2 Implementation of Complex Class #include #include "Complex.h" Complex Complex::operator*(Complex rhs) const { Complex prod; prod.re = (re*rhs.re - im*rhs.im); prod.im = (re*rhs.im + im*rhs.re); return prod; } float Complex::modulus() const { return sqrt(re*re + im*im); } void Complex::print() const { std::cout << "(" << re <<"," << im << ")" << std::endl; } Complex c lass implementation in file Complex.cpp

3 Using the class in a Driver File #include #include "Complex.h" int main() { Complex c1, c2(1), c3(1,2); float x; // overloaded * operator!! c1 = c2 * c3 * c2; // mistake! The compiler will stop here, since the // Re and Imag parts are private. x = sqrt(c1.re*c1.re + c1.im*c1.im); // OK. Now we use an authorized public function x = c1.modulus(); c1.print(); return 0; } A program that uses Complex in file TestComplex.cpp

4 Function Overloading What if we want to multiply a complex number with a scalar? Define another function with the same name but different parameters. class Complex {... Complex operator*(Complex rhs) const; Complex operator*(float k) const;... }; This is called function overloading.

5 Implementation of Complex Class Complex Complex::operator*(Complex rhs) const { Complex prod; prod.re = (re*rhs.re - im*rhs.im); prod.im = (re*rhs.im + im*rhs.re); return prod; } Complex Complex::operator*(float k) const { Complex prod; prod.re = re * k; prod.im = im * k; return prod; } Complex c lass implementation in file Complex.cpp

6 Using the class in a Driver File #include #include "Complex.h" int main() { Complex c1, c2(1), c3(1,2); c1 = c2 * c3 * c2; c1.print(); c1 = c1 * 5; // translated to c1.operator*(5) c1.print(); // How about this? c1 = 5 * c1; // CANNOT translate to 5.operator*(c1) return 0; } A program that uses Complex in file TestComplex.cpp

7 Putting the Scalar to the Left To support multiplying with a scalar on the left, we must define a new function that is outside the class scope. Complex operator*(float k, Complex c) { Complex prod; prod.re = k * re; // Compile Error: cannot access re prod.im = k * im; // Compile Error: cannot access im return prod; } Note that this function has access errors: an outside function cannot access the private members of a class! We can solve this in two ways.

8 Solution 1: Setter/Getter Functions class Complex {... public: // add the following functions to the class void setReal(float x) { re = x; } void setImag(float x) { im = x; } float getReal() const { return re; } float getImag() const { return im; }... };

9 Solution 1: Setter/Getter Functions Complex operator*(float k, Complex c) { Complex prod; prod.setReal(k * c.getReal()); prod.setImag(k * c.getImag()); return prod; }

10 Solution 2: Friend Functions class Complex {... friend Complex operator*(float k, Complex rhs);... }; Declare the outside function as the friend of this class. It can then access the private members of the class.

11 Solution 2: Friend Functions Complex operator*(float k, Complex c) { Complex prod; prod.re = k * re; // Now it is ok prod.im = k * im; // Now it is ok return prod; } Note that the “friend” keyword is not used here. It is only used inside the class (see the previous slide).

12 Friend Classes class A {... }; class B {... friend A; }; A class may declare another class as a friend as well. In that case all member functions of the “befriended” class can access the private members of its friend class “A” can access private members of “B” (but not vice versa!!!)

References References are a type of C++ variable that act as an alias to another variable. A reference variable acts just like the original variable it is referencing. References are declared by using an ampersand (&) between the reference type and the variable name. CENG 213 Data Structures13

Example int n = 5, m = 6; int &rn = n; n = 6; rn = 7, cout << n << rn << m << endl; rn = m; cout << n << rn << m << endl; CENG 213 Data Structures14 You cannot declare a reference without giving a value. Makes n equal to m (doesn't make rn refer to m)

const Reference A const reference will not let you change the value it references (the value cannot be changed using that reference): Example: int n = 5; const int & rn = n; rn = 6; // error!! CENG 213 Data Structures15

References Cannot be Changed Once initialized the reference cannot refer to another variable: Example: int n = 5, m = 6; int & rn = n; rn = m; // makes n equal to 6 // does not change rn to refer // to m CENG 213 Data Structures16

References Must be Initialized Therefore, a reference must be initialized during its declaration: Example: int n = 5; int& rn; // error: uninitialized reference CENG 213 Data Structures17

References vs Pointers Everything that is accomplished by references can be accomplished by pointers but the syntax of references is simpler: Example int n= 5; int &rn = n; int *const p = &n; *p = 6; rn = 6; CENG 213 Data Structures18 Same effect

Pointers and const There are two different ways that pointers and const can be intermixed: 1.Constant pointer 2.Pointer to a constant variable CENG 213 Data Structures19

Constant Pointer A const pointer must be initialized to a value upon declaration, and its value can not be changed. However, because the value being pointed to is still non- const, it is possible to change the value being pointed to via dereferencing the pointer: int *const p = &i; *p = 6;//OK (the pointer is constant - not the value) p = &j; // Not OK (the pointer cannot be updated) CENG 213 Data Structures20

Pointer to a const variable It is also possible to declare a pointer to a constant variable by using the const before the data type: int i, j; const int * p = &i; *p = 6; // it is NOT O.K., because i is //treated as constant when accessed by p. However, it can be changed independently: i = 6; // It is O.K. Also the pointer can point to a different variable: p = &j; // OK. This time the value is constant but the pointer can be changed. CENG 213 Data Structures21

CENG 213 Data Structures22 Parameter Passing In C, all parameters are passed by value (call by value). But C++ offers three options: Call by value (like C) –Copy of data passed to function –Changes to copy do not change original Call by reference (uses & syntax) –Avoids a copy and allows changes to the original Call by constant reference (uses const& syntax) –Avoids a copy and guarantees that actual parameter will not be changed

CENG 213 Data Structures23 Example #include using std::cout; using std::endl; int squareByValue( int ); // pass by value void squareByReference( int & ); // pass by reference int squareByConstReference ( const int & ); // const ref. int main() { int x = 2, z = 4, r1, r2; r1 = squareByValue(x); squareByReference( z ); r2 = squareByConstReference(x); cout << "x = " << x << " z = “ << z << endl; cout << “r1 = " << r1 << " r2 = " << r2 << endl; return 0; }

CENG 213 Data Structures24 Example (cont.) int squareByValue( int a ) { a *= a; // caller's argument not modified return a; } void squareByReference( int &cRef ) { cRef *= cRef; // caller's argument modified } int squareByConstReference (const int& a ) { a *= a; // not allowed (compiler error) return a * a; }

25 Improving the Complex Class #ifndef _Complex_H #define _Complex_H using namespace std; class Complex { float re, im; // by default private public: Complex(float x = 0, float y = 0) : re(x), im(y) { } Complex operator*(const Complex& rhs) const; float modulus() const; void print() const; }; #endif Complex class Interface in the file Complex.h

26 Improving the Complex Class #include #include "Complex.h" Complex Complex::operator*(const Complex& rhs) const { Complex prod; prod.re = (re*rhs.re - im*rhs.im); prod.im = (re*rhs.im + im*rhs.re); return prod; } float Complex::modulus() const { return sqrt(re*re + im*im); } void Complex::print() const { std::cout << "(" << re <<"," << im << ")" << std::endl; } Complex c lass implementation in file Complex.cpp

27 Question Complex& Complex::operator*(const Complex& rhs) const { Complex prod; prod.re = (re*rhs.re - im*rhs.im); prod.im = (re*rhs.im + im*rhs.re); return prod; } What would be the problem if we changed the function to return a reference?

CENG 213 Data Structures28 The uses of keyword const We may encounter const in three different places: 1) Constant reference parameter 2) Constant member function 3) Constant object/variable Complex operator*(const Complex& rhs) const; const Complex c1(3, 4);