Mutability: C++ const usage SWE 332 Fall 2011 Paul Ammann.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

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.
CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Mutability SWE 332 Fall 2011 Paul Ammann. SWE 3322 Data Abstraction Operation Categories Creators Create objects of a data abstraction Producers Create.
1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
CS-1030 Dr. Mark L. Hornick 1 Constructors Copy Constructors.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
Ownership Types for Object Encapsulation Authors:Chandrasekhar Boyapati Barbara Liskov Liuba Shrira Presented by: Charles Lin Course: CMSC 631.
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
Standard library types Practical session # 3 Software Engineering
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Object Oriented Programming (OOP) Lecture No. 11.
Object Oriented Programming (OOP) Lecture No. 10.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
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# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Chapter 9 Classes: A Deeper Look, Part I Part II.
#include guards Practical session #2 Software Engineering
Object Oriented Programming Elhanan Borenstein Lecture #5.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 29: Operator overloading.
CSC241 Object-Oriented Programming (OOP) Lecture No. 5.
Effective C++, 2nd Ed. By Scott Myers. Constructors, Destructors, and Assignment Operators 11.Define a copy constructor and an assignment operator for.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Lecture 7.  There are 2 types of libraries used by standard C++ The C standard library (math.h) and C++ The C++ standard template library  Allows us.
Classes: Defining Your Own Data Types Basic principles in OOP Define a new data type as a class and use objects of a class Member Functions –Constructors.
Classes: A Deeper Look D & D Chapter 9 Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0,
C++ Functions A bit of review (things we’ve covered so far)
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Learning Objectives Pointers as dada members
CS 215 Final Review Ismail abumuhfouz Fall 2014.
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.
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Constructors and Other Tools Dr.
CISC/CMPE320 - Prof. McLeod
Object Based Programming
Initialization List.
Built-In (a.k.a. Native) Types in C++
Overview of C++ Overloading
Constructors and Other Tools
CISC/CMPE320 - Prof. McLeod
Pointers Pointers point to memory locations
Passing Arguments and The Big 5
Object Oriented Programming (OOP) Lecture No. 11
Object Oriented Programming (OOP) Lecture No. 10
SPL – PS3 C++ Classes.
Workshop 1++: A bit of C++
Threads and concurrency / Safety
Presentation transcript:

Mutability: C++ const usage SWE 332 Fall 2011 Paul Ammann

SWE 3322 Java and C++ Differ in Treatment of Mutability C++ uses the const keyword Much more complex than Java final But, of course, much more flexible Basic rule: Use const wherever possible Rationale: Minimize Mutability Same reasons as given by Bloch for Java Sources Some from Kak Most from Meyer’s Effective C++

SWE 3323 C++ const: Minimize Mutability Recalling Bloch’s reasons for Java: Easier to design Easier to implement Easier to use Less prone to error More secure Easier to share Thread safe

SWE 3324 Basic usage of const char greeting[] = “Hello”; char *p = greeting; // non-const pointer // non-const data const char *p = greeting; // non-const pointer // const data char * const p = greeting; // const pointer // non-const data const char * const p = greeting; // const pointer // const data

SWE 3325 More syntax void f1 (const Widget *pw); // f1 takes a pointer to a // constant Widget object void f2( Widget const *pw); // so does f2 Note: It doesn’t matter if you switch the const and the type. But the location of the * is key.

SWE 3326 const_iterator std::vector vec; … // iter acts like a T* const const std::vector ::iterator iter = vec.begin(); *iter = 10; // Ok; changes what iter points to ++iter; // error! iter is const // cIter acts like a const T* std::vector ::const_iterator cIter= vec.begin(); *cIter = 10; // error! *cIter is const ++cIter; //fine, changes cIter

SWE 3327 const function returns class Rational {…} const Rational operator*(const Rational& lhs, const Rational&rhs); // why make return const? Rational a, b, c; … (a*b) = c; // oops! //more likely if (a*b=c) … // meant to say (a*b==c) // use of const results in compiler error

SWE 3328 const member functions class TextBlock { public: const char&operator[](std::size_t position) const // operator[] for { return text[position];} // const objects // Note the code bloat!– can be solved by “casting away constness” char&operator[](std:size_t position) // operator[] for { return text[position];} // non const objects private: std::string text; … TextBlock tb(“Hello”); std::cout << tb[0]; // calls non-const TextBlock::operator[] const TextBlock ctb(“World”); std::cout<< ctb[0] // calls const TextBlock::operator[] void print(const TextBlock& ctb) // in this function, ctb is constant { std::cout <<ctb[0];…} // calls const TextBlock::operator[] tb[0] = ‘x’; // fine – writing a non const TextBlock ctb[0] = ‘x’; // error! - writing a const TextBlock

SWE 3329 Bitwise vs. Logical constness Bitwise constness: member function is const iff it doesn’t modify any of objects data members Doesn’t actually enforce immutability Constant pointers vs. mutable data Logical constness: (preferred) member function may modify bits of the object – as long as client can’t tell keyword mutable used to tell compiler modifications are ok

SWE Prefer pass-by-reference-to- const to pass-by-value C++ default is pass by value: for both parameters and return values can be expensive… bool valStudent(Student s); // pass by value Student plato; bool platoOK = valStudent(plato); // call copy constructor vs. bool valStudent(const Student& s); // no constructor/destructor calls // but still safe

SWE Things to remember Declaring const can help compilers detect usage errors const can be applied to any scope Compilers enforce bitwise constness But you should program with logical constness Prefer pass-by-reference-to-const to pass-by- value more efficient, and avoids other problems (eg slicing)