CS193D Handout 10 Winter 2005/2006 January 23, 2006 Pimp Your Classes

Similar documents
Creating Templates and Implementing Smart Pointers CS193D 2/27/06

And Even More and More C++ Fundamentals of Computer Science

Short Notes of CS201

CS193D Handout 12 Winter 2005/2006 January 30, 2006 Introduction to Templates and The STL

CS201 - Introduction to Programming Glossary By

Assignment 1: grid. Due November 20, 11:59 PM Introduction

const int length = myvector.size(); for(int i = 0; i < length; i++) //...Do something that doesn't modify the length of the vector...

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

QUIZ Friends class Y;

Part 1: Complete XMLElement

COSC 2P95 Lab 5 Object Orientation

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Understanding C/C++ Strict Aliasing

M.EC201 Programming language

Data & Procedure Java review

Basic Templates Intro

C++ Inheritance and Encapsulation

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

The Stack, Free Store, and Global Namespace

Chapter 1 Getting Started

During the course of writing the Matrix class we will cover some interesting C++ topics. Specically: constructors and destructors, operator

Intermediate Programming, Spring 2017*

Supporting Class / C++ Lecture Notes

G52CPP C++ Programming Lecture 9

1 Getting used to Python

Object-Oriented Programming. Lecture 2 Dr Piotr Cybula

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

Value categories. PRvalues. Lvalues

Stream States. Formatted I/O

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Constants, References

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University

Client Code - the code that uses the classes under discussion. Coupling - code in one module depends on code in another module

1 Shyam sir JAVA Notes

Chapter 13: Copy Control. Overview. Overview. Overview

Protection Levels and Constructors The 'const' Keyword

Pointers! Arizona State University 1

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Abstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes.

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CSCI-1200 Data Structures Spring 2018 Exam 1 Solutions

CS1004: Intro to CS in Java, Spring 2005

Object-Oriented Programming, Iouliia Skliarova

Const Correctness. Ali Malik

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Introduction Of Classes ( OOPS )

What is Class? Remember

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

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

Do not write in this area TOTAL. Maximum possible points: 75

Casting in C++ (intermediate level)

Object Oriented Programming COP3330 / CGS5409

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

The vector Class and Memory Management Chapter 17. Bjarne Stroustrup Lawrence "Pete" Petersen Walter Daugherity Fall 2007

More class design with C++ Starting Savitch Chap. 11

CE221 Programming in C++ Part 1 Introduction

Chapter 10 Introduction to Classes

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Upcoming Features in C# Mads Torgersen, MSFT

CS103 Spring 2018 Mathematical Vocabulary

COMP322 - Introduction to C++ Lecture 07 - Introduction to C++ classes

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV

Class 9: Static Methods and Data Members

Super-Classes and sub-classes

Ar r ays and Pointer s

Tutorial 7. Y. Bernat. Object Oriented Programming 2, Spring Y. Bernat Tutorial 7

Member Initializer Lists

Lab 7 Macros, Modules, Data Access Pages and Internet Summary Macros: How to Create and Run Modules vs. Macros 1. Jumping to Internet

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Module Operator Overloading and Type Conversion. Table of Contents

Do not write in this area A.1 A.2 A.3 A.4 A.5 A.6 B.1 B.2 B.3 TOTAL. Maximum possible points:

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

Inheritance (IS A Relationship)

SERIOUS ABOUT SOFTWARE. Qt Core features. Timo Strömmer, May 26,

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Code blocks, inside and out

Constructors for classes

Use mail merge to create and print letters and other documents

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

6.096 Introduction to C++

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

Copy Constructors and Assignment Operators

Assignment 1: SmartPointer

Overview of C Feabhas Ltd 2012

OBJECT ORIENTED PROGRAMMING USING C++

CSCI 102 Fall 2010 Exam #1

CSE 333 Autumn 2014 Midterm Key


CSE143 Exam with answers MIDTERM #1, 1/26/2001 Problem numbering may differ from the test as given.

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

III. Classes (Chap. 3)

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

C++ 8. Constructors and Destructors

Transcription:

CS193D Handout 10 Winter 2005/2006 January 23, 2006 Pimp Your Classes See also: The middle part of Chapter 9 (194-208), Chapter 12 Pretty much any Object-Oriented Language lets you create data members and methods, but only C++ gives you a catalog of keywords you can apply to your classes to create special features. This handout summarizes some of the favorites, both useful and obscure. The static Keyword static, much like our friend const, can be used in several different ways in C++. One of the uses is static data members, which are data members that exist not on a per-object basis, but a per-class basis. Below is a static data member in the Spreadsheet class: class Spreadsheet bool inrange(int val, int upper); void copyfrom(const Spreadsheet& src); int mwidth, mheight; SpreadsheetCell** mcells; static int scounter; Static data members need to be explicitly constructed. This generally goes in the.cpp file: // Spreadsheet.cpp int Spreadsheet::sCounter = 0; The static can be accessed within a method or constructor, just like any other data member. The only difference is that there is only one scounter, no matter which object is looking at it: Spreadsheet::Spreadsheet(const Spreadsheet& src) scounter++; copyfrom(src); 1

Static data members can also be accessed from outside the class (if they're public) by using the scope resolution operator (::). No instance of the class is needed because a static isn't bound to a particular object, it's bound to the class. Methods can be static as well. A method that doesn't apply to a particular instance of a class (for example, a utility method like a conversion routine) can be declared static: static string doubletostring(double val); static double stringtodouble(const string& str); When a method is static, it cannot access non-static data members. Static methods aren't specific to an object, so it would be impossible to determine which object's data members to access. The following line won't compile: // SpreadsheetCell.cpp string SpreadsheetCell::doubleToString(double val) mvalue = 7; // BUG! A static method can't access non-static data! If they are public, static methods can be accessed by other classes, again using the scope resolution operator: // main.cpp string s = SpreadsheetCell::doubleToString(14); const Aren't we done with this yet? Not quite! Imagine the possibilities if we combine static and const! We can put a constant right in a class and make it externally accessible without an instance of the object. class Spreadsheet static const int kmaxheight = 100; static const int kmaxwidth = 100; 2

Note that unlike other data members, C++ lets you initialize const data members inside the class definition if they are of basic types. Otherwise, you have to do it externally, just like initializing any other static: // Spreadsheet.cpp const int Spreadsheet::kMaxHeight = 100; const int Spreadsheet::kMaxWidth = 100; Remember that methods can also be const, indicating that they do not change the underlying object: double getvalue() const; // getters are often const mutable const's nemesis Sometimes, you'll write a method that is logically const, but actually needs to change the class. This modification has no effect on any user-visible data, but is technically a change, so the compiler won t let you declare the method const. For example, if we wanted to keep track of the number of times getvalue() was called, we couldn't do it if getvalue() is const: double SpreadsheetCell::getValue() const mnumberoftimesaccessed++; // BUG! Can't change data member in const method By making mnumberoftimesaccessed mutable, we can tell the compiler, "It's okay. This data member can be changed by a const method": mutable int mnumberoftimesaccessed; Edge Cases with References We've already covered most of the ways that references are used (such as const references those are important!), but here are a few other tidbits about refs: 3

References cannot be bound to a non-variable (int& ref = 2 won't compile) unless the reference itself is const (const int& ref = 2 will compile) References act like pointers, but they aren't pointers (int& xref = &x won't compile). Don't be confused by the & sign it doesn't mean address of! You can have a pointer to a reference (int*& myptrref = intptr is okay) but you cannot have a pointer to a reference (int&* myrefptr = &myref won't compile) or a reference to a reference (int&& myrefref = &myref won't compile) References can be used as data members, but they must be set in the initializer list. friend The feature that only pretends to be your friend Sometimes you feel like you want to get around the whole public versus protected thing and just grant an individual class, method, or function the right to call a method. The friend keyword lets you do this, but you should use it sparingly it's often a sign that your class structure has broken down. Here is an example of a friend class. The SpreadsheetCell class is allowing the Spreadsheet class to use any of its protected and private methods and members: friend class Spreadsheet; Method Overloading In C++, you can have two versions of the same method as long as they differ in their argument lists. For example, setvalue() and setstringvalue() could both be called set():... void set(double invalue); void set(const string& instring); double getvalue() const; string getstring() const; Note that method overloading does not apply to return types. You cannot have two methods with the same name that only differ in their return type: 4

... double get() const; string get() const; // BUG! There is already a get() method 5