Constants, References

Similar documents
Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS 247: Software Engineering Principles. ADT Design

Copy Constructor, Assignment, Equality

Pointers, Dynamic Data, and Reference Types

Implementing Abstract Data Types (ADT) using Classes

Value vs. Entity Objects, Information Hiding

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Object-Oriented Programming, Iouliia Skliarova

Assertions and Exceptions

CS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p.

Object-Oriented Programming, Iouliia Skliarova

ADTs & Classes. An introduction

COMP 2355 Introduction to Systems Programming

Protection Levels and Constructors The 'const' Keyword

QUIZ. What is wrong with this code that uses default arguments?

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Homework #3 CS2255 Fall 2012

Special Member Functions

Constructors.

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

内存管理. Memory management

CS201 Latest Solved MCQs

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CS201- Introduction to Programming Current Quizzes

CMSC 202 Midterm Exam 1 Fall 2015

Object Oriented Software Design II

Intermediate Programming, Spring 2017*

CPSC 427: Object-Oriented Programming

Global & Local Identifiers

NAMESPACES IN C++ You can refer the Programming with ANSI C++ by Bhushan Trivedi for Understanding Namespaces Better(Chapter 14)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Pointers II. Class 31

Review Questions for Final Exam

Come and join us at WebLyceum

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Pointers and References

Object-Oriented Principles and Practice / C++

Tokens, Expressions and Control Structures

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Vector and Free Store (Vectors and Arrays)

Lecture 7. Log into Linux New documents posted to course webpage

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

CS 247: Software Engineering Principles. Modules

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Object Reference and Memory Allocation. Questions:

C How to Program, 6/e, 7/e

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Array Elements as Function Parameters

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

17. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

CPSC 427: Object-Oriented Programming

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

Exam 3 Chapters 7 & 9

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

Abstraction in Software Development

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

What does it mean by information hiding? What are the advantages of it? {5 Marks}

OBJECT ORIENTED PROGRAMMING USING C++

CS24 Week 3 Lecture 1

COMP322 - Introduction to C++

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Ch. 11: References & the Copy-Constructor. - continued -

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Today USING POINTERS. Functions: parameters and arguments. Todaywewilllookattopicsrelatingtotheuseofpointers

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Understand Execution of a Program

17. Classes. Overloading Functions. Operator Overloading. Function Overloading. operatorop

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

19. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Fast Introduction to Object Oriented Programming and C++

Linked List using a Sentinel

EL6483: Brief Overview of C Programming Language

Variables, Memory and Pointers

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

C++ For Science and Engineering Lecture 12

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

FORM 2 (Please put your name and form # on the scantron!!!!)

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

A class is a user-defined type. It is composed of built-in types, other user-defined types and

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

CS 161 Exam II Winter 2018 FORM 1

Scope. Scope is such an important thing that we ll review what we know about scope now:

6.096 Introduction to C++ January (IAP) 2009

CS201 Some Important Definitions

Transcription:

CS 246: Software Abstraction and Specification Constants, References Readings: Eckel, Vol. 1 Ch. 8 Constants Ch. 11 References and the Copy Constructor U Waterloo CS246se (Spring 2011) p.1/14

Uses of const Value substitution (constant must be initialized in its definition) const int size = 256; char input[size]; Assertion that variable won't change value - pointers and const - const function arguments and return values - const in classes - static U Waterloo CS246se (Spring 2011) p.2/14

Scope of a Constant By default, a constant is visible only within the file where it is defined. - scope is smaller if defined inside a function or in a pair of scope braces To define a global constant, we must explicitly define it to be extern(ally) visible. - files that want to use a global constant must use extern declaration File A defines global constant extern const int size = 100; char input[size]; File B declares use of global constant extern const int size; for (int i=0; i<size; i++) {... } U Waterloo CS246se (Spring 2011) p.3/14

Pointers and Constants When the modifier const is applied in pointer definitions. Depending on where the const is placed, either the pointer is constant or its dereferenced variable is constant const int w = 25; const int *p3 = &w; int x = 5; int * const p4 = &x; // alternatively // int &p4 = x; const int z = 37; const int * const p5 = &z; p3 300 25 w p4 100 5 p5 308 37 dashed memory locations are constants x z U Waterloo CS246se (Spring 2011) p.4/14

Pointers and Constants What do the following declarations mean? const int* u; int const* v; int d = 1; int* const w = &d; const int* const x = &d; int const* const x2 = &d; Bruck Eckel, Thinking in C++ Vol. 1 U Waterloo CS246se (Spring 2011) p.5/14

Type Checking and Constants C++ type checking will not allow assignments of const objects to pointers to non-const referents. - because it would allow the const object to be changed via the pointer int d = 1; const int e = 2; int* u = &d; // OK -- d not const //! int* v = &e; // Illegal -- e const int* w = (int*)&e; // Legal but bad practice Bruck Eckel, Thinking in C++ Vol. 1 U Waterloo CS246se (Spring 2011) p.6/14

References A reference (&) is a constant alias for another object. Rational r(3,4); Rational &x = r; cout << "x = " << x << ", r = " << r << endl; x = x + 1; cout << "x = " << x << ", r = " << r << endl; 3 rules for using references: must be initialized when it is created cannot have NULL references once initialized, it cannot be changed to refer to another object U Waterloo CS246se (Spring 2011) p.7/14

References in Functions The most common usage of references is as function arguments and return values. istream& operator>> (istream &sin, Rational &r) { char slash; } sin >> r.numerator_ >> slash >> r.denominator_; return sin; A reference argument is an alias to the object passed in - any change to the reference changes the object outside the function A reference return value is an alias to the object returned. U Waterloo CS246se (Spring 2011) p.8/14

Constant Parameters The const parameter declaration is a guarantee that the routine does not modify the parameter. can apply the function to constants can apply the function to temporary objects (which are constants) void r( const int &i, const int &j, const Rational &r ) { //! i = 3; // compiler errors, arguments are read only! //! r = Rational(3,4); //! v[0] = 3; } // following call is legal r( 10, i + j, Rational(3,4) ); Best Practice: Whenever possible, pass parameters by const reference U Waterloo CS246se (Spring 2011) p.9/14

Constant Function Return Values We declare a function return to be const if we want to prevent the client programmer from modifying the result of a function call. const Rational operator+ (const Rational&, const Rational&){... } int main() { Rational r(1,2); Rational s(1,3); Rational t = r + s; // OK - value is copied to t // (r+s) = r; ERROR - cannot assign to const object } U Waterloo CS246se (Spring 2011) p.10/14

Constant Data Members A const data member is a constant associated with an object - every object may have a different value for constant class StrStack { public:... private: const int STACK_SIZE; string items_ [STACK_SIZE]; int top_; // top of stack }; Initialization is tricky - constant is initialized when its object is created (constructor) - must be initialized before body of constructor executes U Waterloo CS246se (Spring 2011) p.11/14

Constructor Initialization List class StrStack { public: StrStack (int size);... private: const int STACK_SIZE; string items_ [STACK_SIZE]; int top_; // top of stack }; // constructor StrStack::StrStack(int size) : STACK_SIZE(size), top_(-1) { } Syntax resembles "constructor calls" to data member's constructors Initialization occurs before constructor body executes U Waterloo CS246se (Spring 2011) p.12/14

Class Constants Alternatively, may want to define a constant that is associated with a class (and all of its objects) static const must be initialized when defined class StrStack { public:... private: static const int STACK_SIZE = 10; string items_ [STACK_SIZE]; int top_; // top of stack }; U Waterloo CS246se (Spring 2011) p.13/14

Constant Member Functions A constant member function is guaranteed not to change the function's object (*this). can apply the function to constant objects class Rational { public: int numerator() const; void numeratoris(const int);... }; // Accessor // Mutator const Rational s(2,3); cout << s.numerator() << endl; // OK //! s.numeratoris(5); // type error Best Practice: Whenever possible, use const member funcations. U Waterloo CS246se (Spring 2011) p.14/14