Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.

Slides:



Advertisements
Similar presentations
1 C++ Reference Parameters Math 130 B Smith: 40 to 45 min. Rate:3. Important discussion on reference parameters! B Smith: 40 to 45 min. Rate:3. Important.
Advertisements

Chapter 7: User-Defined Functions II
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
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.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Object-Oriented Programming in C++
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Object-Oriented Programming in C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
1 CS161 Introduction to Computer Science Topic #10.
Parameter Passing Mechanisms Reference Parameters § §
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Chapter 8 Operator Overloading, Friends, and References.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
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.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
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?
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
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.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
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.
C++ Functions A bit of review (things we’ve covered so far)
C++ Templates.
Pointers and Pointer-Based Strings
Student Book An Introduction
Templates.
Initialization List.
6 Chapter Functions.
Chapter 4 Implementing Free Functions
Dr. Bhargavi Dept of CS CHRIST
Function “Inputs and Outputs”
Pointers and References
Pointers and Pointer-Based Strings
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Submitted By : Veenu Saini Lecturer (IT)
CMSC 202 Lesson 6 Functions II.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
SPL – PS3 C++ Classes.
Initialization List.
Presentation transcript:

Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading

Introduction Last lecture we looked at functions –syntax, overloading, default arguments, inline expansion header files –need for prototypes, compiling multiple source files This lecture we will look at more aspects of functions –constants, parameter passing and operator overloading introduce reference types

Constants sometimes we want to use constants in a program –data that cannot be changed once defined –use the const keyword const double pi = ; pi = 45.2; // illegal error C3892: 'pi' : you cannot assign to a variable that is const

Constant objects objects can also be marked constant –then none of their attributes are allowed to be changed once initialised a constant Account object should have its balance frozen –you can't withdraw or deposit money, or add interest const Account myAccount(45, 2.4); double bal = myAccount.getBalance(); however, the Account class we have written does not allow ANY member functions to be called on a constant Account object error C2662: 'Account::getBalance' : cannot convert 'this' pointer from 'const Account' to 'Account &'

Constant methods it should be OK to get the balance of a constant account object –as long as we don't change the balance enable this by marking the getBalance() method with the const keyword both the method declaration (prototype) and the definition must be const double getBalance() const; double Account::getBalance() const {return balance;}

Constant methods make sure the constant method does not attempt to alter a member variable! double Account::getBalance()const{ balance -= 0.05; // not allowed return balance; } error C3490: 'balance' cannot be modified because it is being accessed through a const object

Reference types a reference type is like an alias for a data object int myAge = 25; int & yourAge = myAge; yourAge++; // it's your birthday cout << "You are "<< yourAge << " and I am " << myAge << endl; output: You are 26 and I am 26 we must be twins!

Reference types yourAge and myAge reference the same data which is stored at the memory location associated with myAge if myAge goes out of scope, yourAge refers to invalid data myAge knows nothing about yourAge –so is not affected if yourAge goes out of scope

Reference types note: the address values given are arbitrary examples AddressNamevalue yourAge myAge25

Parameter passing in C++, by default all parameters are passed to functions by value a local copy is made of each parameter when the function is called –the local copy goes out of scope when the function returns if the function changes the local copy, the original data in the calling function is unchanged how can we implement a swap function?

Swap function – pass by value void swap(int a, int b) { int temp = a; a = b; b = temp; } int main() { int x =3, y = 5; swap(x, y); cout << "After swap function, x = " << x << " and y = " << y << endl; } After swap function, x = 3 and y = 5

Pass by reference we can't do the swap passing by value we can only return one value from the function, not two the solution is to pass reference types instead the function will alter the data stored by the variables they alias when the function returns, x and y will contain the new values

Swap function – pass by reference void swap(int & a, int & b) { int temp = a; a = b; b = temp; } int main() { int x =3, y = 5; swap(x, y); cout << "After swap function, x = " << x << " and y = " << y << endl; } After swap function, x = 5 and y = 3

Pass by reference when the swap function is called, the parameters a and b are initialised as aliases to x and y void swap(int & a, int & b) initialises int & a = x; int & b = y; when swap returns, the aliases go out of scope and the values of x and y have been changed

Why pass by reference? passing by reference is useful when you: want to change one or more function parameters would like to return more than one value from a function –pass one of them in as a reference, and change it inside the function a parameter is very large, so making a local copy in the function would be wasteful –3D model or image object –when a reference is passed, only the address is copied

Constant references if you pass an object by reference, the function could change it –even if the intention was just to be more efficient using the keyword const ensures that the referenced object can be passed safely the function cannot change the object –can only call its const functions void outputAccount(const Account & a); void outputAccount(const Account & a) { cout << a.getBalance() << endl; }

Pass by value or reference? in Java, the programmer has no choice –primitive types are passed by value the function uses a local copy of the data –Strings, arrays and objects are passed by reference the address is passed to the function the function can manipulate the data in C, the programmer has a choice –passing by value ensures the original data isn't changed –passing by reference allows the data to be updated –passing by value is inefficient with larger data types making a local copy of the data uses memory and take time –can safely pass by constant reference

Operator overloading we have already looked at overloading functions –same name, different parameter list we have seen that common operators are overloaded + - * / > we can write our own operator overloads

Overloading the << operator sends bytes from the variable on the right to the output stream on the left cout << "Hello!" << endl; defined to send bytes from strings, ints, doubles… we could overload the << operator to work with an Account object Account myAccount(45, 2.4); cout << myAccount << endl; Account balance: 45 Interest rate: 2.4

Overloading << << is not a member of the Account or ostream class – define it outside the Account class ostream& operator<< (ostream& os, const Account acc) { os << "Account balance: " << acc.getBalance() << endl << "Interest rate: " << acc.getInterestRate() << endl; return os; } note the use of a different overload of << within the function

Friend functions and operators functions and operators can be declared friends of one or more classes the function has access to the private members of its friends we could declare << to be a friend of Account –in the public section of Account friend ostream& operator<< (ostream& os, const Account acc); and rewrite the operator definition to use private member variables of Account ostream& operator<< (ostream& os, const Account acc) { os << "Account balance: " << acc.balance << endl << "Interest rate: " << acc.interestRate << endl; return os; } is this a good idea? using the friend keyword ties the implementation of this overload of << to the internal implementation of Account

Summary In this lecture we have: looked at more aspects of functions –constants, parameter passing and operator overloading introduced reference types In the tutorial we will split the Account definintion to use header files practice using different types of functions –overloads, constant, friend, operator… experiment with passing by reference and value