A popular USENET joke: In C, you merely shoot yourself in the foot. In C++, you accidentally create a dozen instances of yourself and shoot them all in.

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)

Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Overloading Operators Overloading operators Unary operators Binary operators Member, non-member operators Friend functions and classes Function templates.
Copyright  Hannu Laine C++-programming Part 7 Hannu Laine Static members Different uses of const specifier.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
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.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
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.
1 Lab Session-XIV CSIT121 Spring 2002 b Namespaces b First Class Travel b Lab Exercise 14 (Demo) b Lab Exercise b Practice Problem.
Multiple-Subscripted Array
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
February 11, 2005 More Pointers Dynamic Memory Allocation.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
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+
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
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.
11 Introduction to Object Oriented Programming (Continued) Cats.
Object Oriented Programming (OOP) Lecture No. 11.
Object Oriented Programming (OOP) Lecture No. 10.
C++ Classes and Data Structures Jeffrey S. Childs
Mutability: C++ const usage SWE 332 Fall 2011 Paul Ammann.
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:
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
1 Lecture 3 More about C++. 2 Topic for today More about classMore about class –Init list –Inline functions –Const –Default function parameters –Static.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
CSC241 Object-Oriented Programming (OOP) Lecture No. 5.
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?
The This Pointer Programming in C++ Fall 2008 Dr. David A. Gaitros
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
Object-Based Programming in VB.NET. Must Understand Following: Encapsulation Information hiding Abstract Data Type Class, Instance, Reference Variable.
1 Object-Oriented Programming Using C++ A tutorial for pointers.
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.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
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.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0,
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Yan Shi CS/SE 2630 Lecture Notes
Motivation for Generic Programming in C++
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?
Templates.
Motivation and Overview
CS31 Discussion 1E Jie(Jay) Wang Week5 Oct.27.
University of Central Florida COP 3330 Object Oriented Programming
Pointers and Pointer-Based Strings
Student Book An Introduction
Templates.
CISC/CMPE320 - Prof. McLeod
Object Oriented Programming COP3330 / CGS5409
Reference Parameters.
Object Oriented Programming Using C++
Friends, Overloaded Operators, and Arrays in Classes
Today’s Topic Const Ref:
Pointers and Pointer-Based Strings
CMSC 202 Lesson 6 Functions II.
Object Oriented Programming (OOP) Lecture No. 10
Presentation transcript:

A popular USENET joke: In C, you merely shoot yourself in the foot. In C++, you accidentally create a dozen instances of yourself and shoot them all in the foot. Providing emergency medical care is impossible, because you can't tell which are bitwise copies and which are just pointing at others and saying, "That's me, over there."

 Using const is a hassle, but NOT using const can be a bigger problem for you and your client. ◦ Some say: "You can either buy leaky pens and wear a pocket protector, or just buy pens that don't leak, period." ◦ However, when you're writing code, you're not buying pens - you're manufacturing pens for other people to stick in their pockets. Using const helps in manufacturing quality pens that don't leak.

 Guarantees data integrity ◦ Exercise your right to say "NO! You can't change this value, and NO! I won't change yours." It's only five little letters and a whitespace token.  Makes debugging easier (brings errors closer to the compiler)

#include #include "monkey.h" using namespace std; class MonkeyHouse { public: bool containsMonkey( string & name ); //Will it change the value of my name? void addMonkey( Monkey* m ); //Will it change the value of my Monkey? void removeMonkey( Monkey* m ); //Will it change the value of my Monkey? Monkey * getMonkey( string &name ); private: map myMonkeys; }; //if the answer is yes, then when does it change my values -- before or after they //perform is expected function?

1. int I = 1; 2. const int I = 2; 3. const int* I = 3; 4. int const * I = 3; 5. int* const I = 2; 6. const int* const I = 1; 7. const int& I = 2; 8. int& const I = 2;

const int x; // constant int x = 2; // illegal - can't modify x const int* pX; // changeable pointer to constant int *pX = 3; // illegal - can't use pX to modify an int pX = &someOtherIntVar; // legal - pX can point somewhere else int* const pY; // constant pointer to changeable int *pY = 4; // legal - can use pY to modify an int pY = &someOtherIntVar; // illegal - can't make pY point elsewhere const int* const pZ; // const pointer to const int *pZ = 5; // illegal - can't use pZ to modify an int pZ = &someOtherIntVar; // illegal - can't make pZ point elsewhere

 A const object must remain const for the remainder of its life.  There is more than one way to make an object constant (example uses class Monkey objects) ◦ declare it const  map myMonkeys; ◦ pass it to a function as const  void Monkey::addMonkey( const Monkey* const m ); ◦ return it from a function as const  const Monkey * GetMonkey( const string &name );

 All or nothing  Once an object is constant, for the rest of its life, it can: ◦ call const member functions only ◦ be passed to functions that accept const only ◦ be returned from functions as const only

 To function parameters that will not change data ◦ bool containsMonkey( const string & name );  note: you now have a const reference  To function parameter pointers that will not change pointer location ◦ void addMonkey( const Monkey* const m );  note: you now have a const pointer

 To functions that are called by const objects (because you have to) ◦ string GetName() const;  because you now have const objects that need it  To return values for const objects (because you have to) ◦ const Monkey * GetMonkey( const string &name );  because your Monkey is now const

class Person { public: Person(char* szNewName) ~Person() { delete[] m_szName; }; const char* const GetName() //return value is const, not the function { return m_szName; }; private: char* m_szName; }; //Non Member function implementation void PrintPerson(const Person* const pThePerson)//accepts a const object { // error - non-const member function called cout GetName() << endl; //const object's non-const member function }

class Person { public: Person(char* szNewName) ~Person() { delete[] m_szName; }; const char* const GetName() const private: char* m_szName; }; //Non Member function implementation void PrintPerson(const Person* const pThePerson) //takes const object { // no error - const member function called cout GetName() << endl; //const object's const member function }

 You guarantee (and the compiler will make sure of it) that not a single modification can or will be made for the members of the class in your function.  a const member function will not invoke other member functions that are not const. ◦ Const must be maintained until function returns ◦ If a function can't change an object, it can only call other functions that won't change it either  Const functions will accept and return reference and/or pointers to objects if they are const

 What is overloading? ◦ More than one version of the same function  Why overload? ◦ A non-const function can return a const or a non- const reference or pointer but... ◦ When const functions return objects (ie. references or pointers to members of the class) they must also be const and... ◦ You have const and non-const objects that need the function

int Loan::calcInterest() const //const function returns int { return loan_value * interest_rate; } int& myClass::getData() //non-const function returns non-const & { return data; } const int& myData::getData() const //const function returns const & { return data; }

 Overload a list_search function that traverses a linked list and returns a reference to a node. A const and non-const version of a list_search function could be used as a subtask of: ◦ display a data item from the list (const) ◦ updating data item in a node (non-const) ◦ insert new node in middle or end of list (non-const)  Examples from the text can be found on p. 236 and 316

Cplusplus/2/