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.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Copyright  Hannu Laine C++-programming Part 7 Hannu Laine Static members Different uses of const specifier.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
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.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
Chapter 14: Overloading and Templates
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Learners Support Publications Classes and Objects.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Object Orientation A Crash Course Intro. What is an Object? An object, in the context of object- oriented programming, is the association of a state with.
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.
CS 31 Discussion, Week 8 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:00-1:00pm.
More C++ Features True object initialisation
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
1 Chapter 1 C++ Basics Review Reading: Sections 1.4 and 1.5.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
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 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
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.
Recap Stale Pointers and Double Delete Reference Variables Reference Type vs Pointer Type Structures Pointers to Structures Exogenous vs Indigenous Data.
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.
CHAPTER 07 Arrays and Vectors (part II). OBJECTIVES In this part you will learn:  To pass arrays to functions.  Basic searching techniques.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
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.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
User-Written Functions
Chapter 1 C++ Basics Review
Java Programming: Guided Learning with Early Objects
Pointers and Pointer-Based Strings
Student Book An Introduction
Advanced Programming Behnam Hatami Fall 2017.
METHODS AND BEHAVIORS AKEEL AHMED.
Dr. Bhargavi Dept of CS CHRIST
Classes and Objects.
Pointers and Pointer-Based Strings
Java Programming Language
Submitted By : Veenu Saini Lecturer (IT)
Presentation transcript:

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 program. – Even when working with fixed values, it is best to abstract them with variable names. It’s more helpful (debugging-wise) to see “array_length” than tons of copies of the same number everywhere.

Humble Beginnings With object-orientation, many classes may take permanent values which are unique to each instance of the class, specified during initialization. – As these should not change at any point in the object’s lifetime, const makes sense.

Humble Beginnings The use of const is fairly straightforward for the primitive data types – the basic building blocks of the language. Things get more complicated when we use const with pointers and with objects.

const and Objects What would it mean for an object to be const ?

const and Objects What would it mean for an object to be const ? – If declared const, an object should not be modifiable. – Problem: how can we use its methods while being sure not to modify it?

const and Objects In C++, whenever a variable is declared const, no modifications are allowed to it, in a by-value manner. – As the compiler is not powerful enough to ensure that its methods do not modify it, by default C++ blocks all use of any class methods. This would be a huge problem for encapsulation.

const and Objects The C++ solution to the problem this poses: functions can be declared const. – Appending the const keyword to a function signifies that the method is not allowed to alter the class in any manner. – Inside that method, all fields of the class will be treated as if they were declared const.

const and Objects Let us now examine how this would look in code, through our frequent Person class example.

A First Object public class Person { private: const string name; int age; public: Person(string name, int age) string getName() const; int getAge() const; void haveABirthday(); }

A First Object string Person::getName() const { return this->name; } int Person::getAge() const { return this->age; }

A First Object public void haveABirthday() { this->age++; } Note: declaring this method as const would result in a compile-time error, as age would be treated as const within the method.

const and Objects Which of the following code lines is invalid? const Person p(“Joshua”, 28); string name = p.getName(); int age = p.getAge(); p.haveABirthday();

const and Objects Which of the following code lines is invalid? p.haveABirthday(); As this method is not declared const, a compile-time error would result from this method being called upon const p.

Exercise 1 Bust out your Person code and modify it to make const methods Modify your main() to declare a const person object Try to access the object with all methods Compile & run Fix

const and Pointers When we add pointers into the mix, things get even more interesting. – What might we wish to be constant? The stored address / pointer The referenced value

const and Pointers In order to have a const pointer to a changeable value, use the following syntax: – int* const myVariable ; To allow the stored address to be replaced, but have the referenced value be otherwise unchangeable: – const int* myVariable ;

const and Pointers Using the syntax below, while obj is declared by-reference, the compiler will block any attempts to modify its contents: – const Object* obj ; – The referenced object obj is considered constant.

const and Pointers The simplest way to think of it – read const definitions from right to left. – int* const myVariable ; – const int* myVariable ; When const is fully on the left, it modifies the direct right instead. int const* myVariable; – Is the same definition, with different ordering.

const and Pointers While very powerful, const syntax can get rather crazy: – const Object* const obj ; – Translation: const Object* const obj ; A const reference… const Object* const obj ; to a const Object.

const and Pointers Similar rules apply to arrays. – The following may store a constant reference to an array with changeable values: int* const myVariable ; – The following may store a replaceable reference to arrays whose values are treated as const : const int* myVariable ;

const and Pointers Example: int* initArray = new int[6]; int* const myVariable = initArray; myVariable = new int[3]; //Above: Not legal myVariable[2] = 3; // Legal! …

const and Pointers Example: int* initArray = new int[6]; const int* myVariable = initArray; myVariable = new int[3]; //Above: Legal, not initialized myVariable[2] = 3; //Illegal! …

Exercise 2 Code up the previous examples with four int arrays – Non-const – Const int* – Int* const – Const int* const Code main() to access each of the array types in each way Compile, observe, comment out code that compiler doesn’t like

const and Parameters Suppose a method is defined as follows: void someMethod(const Object* obj) What implications would this have?

const and Parameters void someMethod(const Object* obj) What implications would this have? – As obj is defined const Object*, we would get a pointer to an unmodifiable instance of Object. – What are we able to pass in as an argument to obj ?

const and Parameters void someMethod(const Object* obj) Which of these would be proper calls? – const Object obj(); someMethod(&obj); – Object* obj = new Object(); someMethod(obj);

const and Parameters void someMethod(const Object* obj) Which of these would be proper calls? – const Object obj(); someMethod(&obj); – Object* obj = new Object(); someMethod(obj); Trick Question! Both!

const and Parameters void someMethod(const Object* obj) While the original argument to methods of this form do not have to be const, they become const within the method.

const and Parameters void someMethod(Object* obj) Which of these would be proper calls? – const Object obj(); someMethod(&obj); – Object* obj = new Object(); someMethod(obj);

const and Parameters void someMethod(Object* obj) Which of these would be proper calls? – const Object obj(); someMethod(&obj); – Object* obj = new Object(); someMethod(obj);

const and Parameters const objects cannot be passed by- reference to non- const function parameters. – As there is no guarantee that the referenced object will not be modified when passed to a non- const parameter, the compiler blocks this. – For value types, since a separate value is created, that separate copy is safe for the called function to edit.

const and Parameters const objects cannot be passed by- reference to non- const function parameters. – An interesting consequence of this: void someMethod(string &str); someMethod(string(“Hello World”)); // Will be a compile-time error // due to the compile-time constant.

const and Parameters const objects cannot be passed by- reference to non- const function parameters. – An interesting consequence of this: void someMethod(const string &str); someMethod(string(“Hello World”)); // Will work without issue!

const and Parameters A signature of the latter type – void someMethod(const string &str) has one additional benefit. – Since str is passed by reference here, the system doesn’t have to copy its value… – And since str is declared const, its value cannot be changed.

const and Parameters A signature of the latter type – void someMethod(const string &str) has one additional benefit. – Consider if this were a very large string. Or, just some very large object. – This makes the program more efficient in terms of run-time and in terms of memory use.

const and Return Values const may also be applied to return values! – Consider if we were to return a reference to an object’s internal field. – Rather than copy the internal object, we may wish to return it while blocking write access within the object. Example: const Object* gimmeObject();

const and Return Values While not mentioned thus far in class, this also affects the other return-by-reference type… const Object& gimmeObject(); This form, if not const, allows code to both modify that object and assign directly to its original variable!

Exercise 3 Code const and non-const parameter methods for some object Try passing const and non-const instances into the methods Compile and observe

const Design const allows the programmer to share values freely with other parts of the program while making them write-only. – This can be very useful for encapsulation! Return an array/internal reference “const type*” – the same array is used, but edits are prohibited!