Object Oriented Software Design II



Similar documents
Object Oriented Software Design II

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

C++ Overloading, Constructors, Assignment operator

The C Programming Language course syllabus associate level

Informatica e Sistemi in Tempo Reale

Object Oriented Software Design II

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

C++FA 5.1 PRACTICE MID-TERM EXAM

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Design Patterns in C++

C++ Programming Language

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Object Oriented Software Design

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

An Incomplete C++ Primer. University of Wyoming MA 5310

Object Oriented Software Design

Chapter 13 Storage classes

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

C++ INTERVIEW QUESTIONS

Sources: On the Web: Slides will be available on:

Moving from CS 61A Scheme to CS 61B Java

Variable Base Interface

N3458: Simple Database Integration in C++11

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Class 16: Function Parameters and Polymorphism

Habanero Extreme Scale Software Research Project

OpenCL Static C++ Kernel Language Extension

Stack Allocation. Run-Time Data Structures. Static Structures

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

1 Abstract Data Types Information Hiding

Fundamentals of Programming

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Chapter 5 Names, Bindings, Type Checking, and Scopes

El Dorado Union High School District Educational Services

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Tutorial on C Language Programming

CISC 181 Project 3 Designing Classes for Bank Accounts

Basics of C++ and object orientation in OpenFOAM

Crash Course in Java

Course notes Standard C++ programming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Keil C51 Cross Compiler

Functions and Parameter Passing

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Course Title: Software Development

Comp151. Definitions & Declarations

C++ Crash Kurs. C++ Object-Oriented Programming

CS 241 Data Organization Coding Standards

C++FA 3.1 OPTIMIZING C++

Visual Basic Programming. An Introduction

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

MPI-Checker Static Analysis for MPI

Java CPD (I) Frans Coenen Department of Computer Science

Glossary of Object Oriented Terms

Curriculum Map. Discipline: Computer Science Course: C++

Elemental functions: Writing data-parallel code in C/C++ using Intel Cilk Plus

Object Oriented Software Design

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Applied Informatics C++ Coding Style Guide

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

Semantic Analysis: Types and Type Checking

Common Beginner C++ Programming Mistakes

MPLAB Harmony System Service Libraries Help

C Compiler Targeting the Java Virtual Machine

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Lecture 5: Java Fundamentals III

CORBA Programming with TAOX11. The C++11 CORBA Implementation

CSC Software II: Principles of Programming Languages

The programming language C. sws1 1

Cours de C++ Utilisations des conteneurs

Ch 7-1. Object-Oriented Programming and Classes

Beyond the Mouse A Short Course on Programming

Java (12 Weeks) Introduction to Java Programming Language

A brief introduction to C++ and Interfacing with Excel

Chapter One Introduction to Programming

Netscape Internet Service Broker for C++ Programmer's Guide. Contents

Java Crash Course Part I

Goals for This Lecture:

X86-64 Architecture Guide

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

CEC225 COURSE COMPACT

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Install Java Development Kit (JDK) 1.8

Appendix K Introduction to Microsoft Visual C++ 6.0

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Transcription:

Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 1 / 42

Outline 1 Pointers 2 References 3 Copy constructor 4 Static 5 Constants G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 2 / 42

Outline 1 Pointers 2 References 3 Copy constructor 4 Static 5 Constants G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 3 / 42

Pointers We can define a pointer to an object class A {... }; A myobj; A *p = &myobj; Pointer p contains the address of myobj G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 4 / 42

Pointers We can define a pointer to an object class A {... }; A myobj; A *p = &myobj; Pointer p contains the address of myobj As in C, in C++ pointers can be used to pass arguments to functions void fun(int a, int *p) { a = 5; *p = 7; }... int x = 0, y = 0; fun(x, &y); x is passed by value (i.e. it is copied into a), so this assignment only modifies the copy G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 4 / 42

Pointers We can define a pointer to an object class A {... }; A myobj; A *p = &myobj; Pointer p contains the address of myobj As in C, in C++ pointers can be used to pass arguments to functions void fun(int a, int *p) { a = 5; *p = 7; }... int x = 0, y = 0; fun(x, &y); x is passed by value (i.e. it is copied into a), so this assignment only modifies the copy y is passed by address (i.e. we pass its address, so that it can be modified inside the function) G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 4 / 42

Pointers We can define a pointer to an object class A {... }; A myobj; A *p = &myobj; Pointer p contains the address of myobj As in C, in C++ pointers can be used to pass arguments to functions void fun(int a, int *p) { a = 5; *p = 7; }... int x = 0, y = 0; fun(x, &y); x is passed by value (i.e. it is copied into a), so this assignment only modifies the copy y is passed by address (i.e. we pass its address, so that it can be modified inside the function) After the function call, x=0, y=7 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 4 / 42

Another example pointerarg.cpp class MyClass { int a; public: MyClass(int i) { a = i; } void fun(int y) { a = y; } int get() { return a; } }; void g(myclass c) { c.fun(5); } void h(myclass *p) { p->fun(5); } int main() { MyClass obj(0); } cout << "Before calling g: obj.get() = " << obj.get() << endl; g(obj); cout << "After calling g: obj.get() = " << obj.get() << endl; h(&obj); cout << "After calling h: obj.get() = " << obj.get() << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 5 / 42

What happened Function g() takes an object, and makes a copy c is a copy of obj g() has no side effects, as it works on the copy Function h() takes a pointer to the object it works on the original object obj, changing its internal value G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 6 / 42

More on pointers It is also possible to define pointers to functions: The portion of memory where the code of a function resides has an address; we can define a pointer to this address void (*funcptr)(); int (*anotherptr)(int) // pointer to void f(); // pointer to int f(int a); void f(){...} funcptr = &f(); funcptr = f; (*funcptr)(); // now funcptr points to f() // equivalent syntax // call the function G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 7 / 42

Pointers to functions II To simplify notation, it is possible to use typedef: typedef void (*MYFUNC)(); typedef void* (*PTHREADFUN)(void *); void f() {... } void *mythread(void *) {... } MYFUNC funcptr = f; PTHREADFUN pt = mythread; It is also possible to define arrays of function pointers: void f1(int a) {} void f2(int a) {} void f3(int a) {}... void (*functable []) (int) = {f1, f2, f3};... for (int i =0; i<3; ++i) (*functable[i])(i + 5); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 8 / 42

Field dereferencing When we have to use a member inside a function through a pointer class Data { public: int x; int y; }; Data aa; // object Data *pa = &aa; // pointer to object pa->x; // select a field (*pa).y; // " " G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 9 / 42

Outline 1 Pointers 2 References 3 Copy constructor 4 Static 5 Constants G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 10 / 42

References In C++ it is possible to define a reference to a variable or to an object int x; int &rx = x; // variable // reference to variable MyClass obj; // object MyClass &r = obj; // reference to object r is a reference to object obj WARNING! C++ uses the same symbol & for two different meanings! Remember: when used in a declaration/definition, it is a reference when used in an instruction, it indicates the address of a variable in memory G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 11 / 42

References vs pointers There is quite a difference between references and pointers MyClass obj; // the object MyClass &r = obj; // a reference MyClass *p; // a pointer p = &obj; // p takes the address of obj obj.fun(); r.fun(); p->fun(); MyClass obj2; p = & obj2; r = obj2; MyClass &r2; // call method fun() // call the same method by reference // call the same method by pointer // another object // p now points to obj2 // compilation error! Cannot change a reference! // compilation error! Reference must be initialized Once you define a reference to an object, the same reference cannot refer to another object later! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 12 / 42

Reference vs pointer In C++, a reference is an alternative name for an object Pointers Pointers are like other variables Can have a pointer to void Can be assigned arbitrary values It is possible to do arithmetic What are references good for? G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 13 / 42

Reference vs pointer In C++, a reference is an alternative name for an object Pointers Pointers are like other variables Can have a pointer to void Can be assigned arbitrary values It is possible to do arithmetic What are references good for? References Must be initialised Cannot have references to void Cannot be assigned Cannot do arithmetic G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 13 / 42

Reference example referencearg.cpp class MyClass { int a; public: MyClass(int i) { a = i; } void fun(int y) { a = y; } int get() { return a; } }; void g(myclass c) { c.fun(5); } void h(myclass &c) { c.fun(5); } int main() { MyClass obj(0); } cout << "Before calling g: obj.get() = " << obj.get() << endl; g(obj); cout << "After calling g: obj.get() = " << obj.get() << endl; h(obj); cout << "After calling h: obj.get() = " << obj.get() << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 14 / 42

Differences Notice the differences: Method declaration: void h(myclass &c); instead of void h(myclass *p); Method call: h(obj); instead of h(&obj); In the first case, we are passing a reference to an object In the second case, the address of an object References are much less powerful than pointers However, they are much safer than pointers The programmer cannot accidentally misuse references, whereas it is easy to misuse pointers G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 15 / 42

Outline 1 Pointers 2 References 3 Copy constructor 4 Static 5 Constants G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 16 / 42

Copying objects In the previous example, function g() is taking a object by value void g(myclass c) {...}... g(obj); The original object is copied into parameter c The copy is done by invoking the copy constructor MyClass(const MyClass &r); If the user does not define it, the compiler will define a default one for us automatically The default copy constructor just performs a bitwise copy of all members Remember: this is not a deep copy! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 17 / 42

Example Let s add a copy constructor to MyClass, to see when it is called./examples/02.basics-examples/copy1.cpp Now look at the output The copy constructor is automatically called when we call g() It is not called when we call h() G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 18 / 42

Usage The copy constructor is called every time we initialise a new object to be equal to an existing object MyClass ob1(2); // call constructor MyClass ob2(ob1); // call copy constructor MyClass ob3 = ob2; // call copy constructor We can prevent a copy by making the copy constructor private: // can t be copied! class MyClass { MyClass(const MyClass &r); public:... }; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 19 / 42

Const references Let s analyse the argument of the copy constructor MyClass(const MyClass &r); The const means: This function accepts a reference however, the object will not be modified: it is constant the compiler checks that the object is not modified by checking the constness of the methods As a matter of fact, the copy constructor does not modify the original object: it only reads its internal values in order to copy them into the new object If the programmer by mistake tries to modify a field of the original object, the compiler will give an error G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 20 / 42

Outline 1 Pointers 2 References 3 Copy constructor 4 Static 5 Constants G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 21 / 42

Meaning of static In C/C++ static has several meanings for global variables, it means that the variable is not exported in the global symbol table to the linker, and cannot be used in other compilation units for local variables, it means that the variable is not allocated on the stack: therefore, its value is maintained through different function instances for class data members, it means that there is only one instance of the member across all objects a static function member can only act on static data members of the class G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 22 / 42

Static members We would like to implement a counter that keeps track of the number of objects that are around we can use a static variable int ManyObj::count = 0; class ManyObj { static int count; int index; public: ManyObj(); ~ManyObj(); }; int getindex(); static int howmany(); ManyObj::ManyObj() { index = count++; } ManyObj::~ManyObj() { count--; } int ManyObj::getIndex() { return index; } int ManyObj::howMany() { return count; } G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 23 / 42

Static members int main() { ManyObj a, b, c, d; ManyObj *p = new ManyObj; ManyObj *p2 = 0; cout << "Index of p: " << p->getindex() << "\n"; { ManyObj a, b, c, d; p2 = new ManyObj; cout << "Number of objs: " << ManyObj::howMany() << "\n"; } cout << "Number of objs: " << ManyObj::howMany() << "\n"; delete p2; delete p; cout << "Number of objs: " << ManyObj::howMany() << "\n"; } Index of p: 4 Number of objs: 10 Number of objs: 6 Number of objs: 4 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 24 / 42

Static members There is only one copy of the static variable for all the objects All the objects refer to this variable How to initialize a static member? cannot be initialized in the class declaration the compiler does not allocate space for the static member until it is initiliazed So, the programmer of the class must define and initialize the static variable G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 25 / 42

Static data members Static data members need to be initialized when the program starts, before the main is invoked they can be seen as global initialized variables (and this is how they are implemented) This is an example // include file A.hpp class A { static int i; public: A(); int get(); }; // src file A.cpp #include "A.hpp" int A::i = 0; A::A() {...} int A::get() {...} G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 26 / 42

Initialization It is usually done in the.cpp file where the class is implemented int ManyObj::count = 0; ManyObj::ManyObj() { index = count++;} ManyObj::~ManyObj() {count--;} int ManyObj::getIndex() {return index;} int ManyObj::howMany() {return count;} There is a famous problem with static members, known as the static initialization order failure G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 27 / 42

The static initialization fiasco When static members are complex objects, that depend on each other, we have to be careful with the order of initialization initialization is performed just after the loading, and before the main starts. Within a specific translation unit, the order of initialization of static objects is guaranteed to be the order in which the object definitions appear in that translation unit. The order of destruction is guaranteed to be the reverse of the order of initialization. However, there is no guarantee concerning the order of initialization of static objects across translation units, and the language provides no way to specify this order. (undefined in C++ standard) If a static object of class A depends on a static object of class B, we have to make sure that the second object is initialized before the first one G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 28 / 42

Solutions The Nifty counter (or Schwartz counter) technique Used in the standard library, quite complex as it requires an extra class that takes care of the initialization The Construction on first use technique Much simpler, use the initialization inside function G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 29 / 42

Construction on first use It takes advantage of the following C/C++ property Static objects inside functions are only initialized on the first call Therefore, the idea is to declare the static objects inside global functions that return references to the objects themselves access to the static objects happens only through those global functions (see Singleton) G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 30 / 42

Copy constructors and static members What happens if the copy constructor is called? void func(manyobj a) {... } void main() { ManyObj a; func(a); cout << "How many: " << ManyObj::howMany() << "\n"; } What is the output? G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 31 / 42

Copy constructors and static members What happens if the copy constructor is called? void func(manyobj a) {... } void main() { ManyObj a; func(a); cout << "How many: " << ManyObj::howMany() << "\n"; } What is the output? Solution in./examples/02.basics-examples/manyobj.cpp G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 31 / 42

Outline 1 Pointers 2 References 3 Copy constructor 4 Static 5 Constants G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 32 / 42

Constants In C++, when something is const it means that it cannot change. Period. Now, the particular meanings of const are a lot: Don t to get lost! Keep in mind: const = cannot change Another thing to remember: constants must have an initial (and final) value! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 33 / 42

Constants - I As a first use, const can substitute the use of #define in C whenever you need a constant global value, use const instead of a define, because it is clean and it is type-safe #define PI 3.14 // C style const double pi = 3.14; // C++ style In this case, the compiler does not allocate storage for pi In any case, the const object has an internal linkage G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 34 / 42

Constants - II You can use const for variables that never change after initialization. However, their initial value is decided at run-time const int i = 100; const int j = i + 10; int main() { cout << "Type a character\n"; const char c = cin.get(); const char c2 = c + a ; cout << c2; Compile-time constants run-time constants } c2++; ERROR! c2 is const! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 35 / 42

Constant pointers There are two possibilities the pointer itself is constant the pointed object is constant int a int * const u = &a; const int *v; the pointer is constant the pointed object is constant (the pointer can change and point to another const int!) Remember: a const object needs an initial value! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 36 / 42

Const function arguments An argument can be declared constant. It means the function can t change it it s particularly useful with references class A { public: int i; }; void f(const A &a) { a.i++; // error! cannot modify a; } You can do the same thing with a pointer to a constant, but the syntax is messy. G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 37 / 42

Passing by const reference Remember: we can pass argument by value, by pointer or by reference in the last two cases we can declare the pointer or the reference to refer to a constant object: it means the function cannot change it Passing by constant reference is equivalent, from the user point of view, to passing by value From an implementation point of view, passing by const reference is much faster!! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 38 / 42

Constant member functions A member function can be declared constant It means that it will not modify the object class A { int i; public: int f() const; void g(); }; void A::f() const { i++; // ERROR! this function cannot // modify the object return i; // Ok } G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 39 / 42

Constant member functions II The compiler can call only const member functions on a const object! const A a =...; a.f(); a.g(); // Ok // ERROR!! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 40 / 42

Constant return value This is tricky! We want to say: the object we are returning from this function cannot be modified This is meaningless when returning predefined types const int f1(int a) {return ++a;} int f2(int a) {return ++a;} int i = f1(5); i = f2(5); // legal these two functions are equivalent! const int j = f1(5); // also legal const int k = f2(5); //also legal G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 41 / 42

Return mechanism When returning a value, the compiler copies it into an appropriate location, where the caller can use it int f2(int a) { return ++a; } int i = f2(5); 1 a is allocated on the stack 2 the compiler copies 5 into a 3 a is incremented 4 the modified value of a is then copied directly into i 5 a is de-allocated (de-structed) why const does not matter? since the compiler copies the value into the new location, who cares if the original return value is constant? It is deallocated right after the copy! For objects, it is much more complex... (next lecture) G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26, 2012 42 / 42