object oriented programming in iso c++ -...

68
Object Oriented Programming in ISO C++ Jacques Farré [email protected] http://deptinfo.unice.fr/~jf/C++/EN Université de Nice – Sophia Antipolis

Upload: trankiet

Post on 13-May-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

Object Oriented Programming in ISO C++

Jacques Farré

[email protected]://deptinfo.unice.fr/~jf/C++/EN

Université de Nice – Sophia Antipolis

I. Guided tour and basic concepts 2/68OOP in C++ © JacquesFarré UNS 2012

Course summary

I. Guided tour of C++ and basic concepts of programming languages

II. Classes & Objects

III. Inheritance, Polymorphism & Introduction to templates

I. Guided tour and basic concepts 3/68OOP in C++ © JacquesFarré UNS 2012

Bibliography

Good starting point– C++ Primer (5th Edition). Lippman, Lajoie,

and Moo. Addison-Wesley Professional 2012

– Thinking in C++. Eckel. Prentice Hall (http://mindview.net/Books/TICPP/ThinkingInCPP2e.html)

– Programming: Principles and Practice Using C++. Stroustrup. Addison-Wesley Professional 2008

– Effective C++ and More Effective C++. Meyers. Addison Wesley Professional 2005

I. Guided tour and basic concepts 4/68OOP in C++ © JacquesFarré UNS 2012

Prehistory & History of C++ (I)

Bjarne Stroustrup (AT&T Bell Labs) End of 70’s : C with classes

– Inspired by the concept of class in Simula 67– Based on C for its efficiency

Numerous improvements leading to C++ (mid 80’s)

90’s : ISO standardization process– still extensions deemed necessary by the

user, complicating even more the language–

I. Guided tour and basic concepts 5/68OOP in C++ © JacquesFarré UNS 2012

Prehistory & History of C++ (II)

Nowdays: ISO C++– Standardized language– Standard Template Library (STL)– Language now quite stable– Compilers mostly up to date– Latest version : C++11

Language of primary importance in the software industry

But not a language easy to handle

I. Guided tour and basic concepts 6/68OOP in C++ © JacquesFarré UNS 2012

Legacy of C++

Lisp

Algol 60

Simula 67

Algol 68

CAda

Pascal

C++

SmalltalkCLOS

JavaC#

Objective CPython

I. Guided tour and basic concepts 7/68OOP in C++ © JacquesFarré UNS 2012

Programming & Abstraction

Continuous evolution of programing techniques towards more abstraction &more structuration

Abstraction / structuration can be done by– procedures and functions (Fortran, Algol,

Pascal, C ...)– modularity (Modula, PL/1 ...)– abstracts data types (Ada, Modula-2 ...)– classes, généricity, type hierarchy : Object

Oriented languages

I. Guided tour and basic concepts 8/68OOP in C++ © JacquesFarré UNS 2012

Variations on a stack

Abstract view of a stack : 4 operations– push an object onto the stack– pop the objet from stack top– enquire if the stack is empty– enquire if the stack is full

A possible implémentation– fixed size array– pointer to the stack top

⇒ a stack class

Push

0

N-1

tab

topPop

I. Guided tour and basic concepts 9/68OOP in C++ © JacquesFarré UNS 2012

The basic Stack class

A class– allows to group data (attributes) and

operations (methods) on these data

– allows to control access to members (attributes, methods) of the class

– allows to create consistent instances of the class thanks to constructors

I. Guided tour and basic concepts 10/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { // a stack of integers (10 max) public : Stack (); // (default) constructor

bool is_full () const; // object state bool is_empty () const; // consultation

int pop (); // object state void push (int); // modification

protected : static const int N = 10; int tab [N]; int top;};

#endif#endif

The basic Stack

class :

specification

always remember to

avoid multiple

inclusions of a same .h by

#ifndef XXX#ifndef XXX#define XXX#define XXX……#endif#endif

I. Guided tour and basic concepts 11/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack (); // (default) constructor

bool is_full () con bool is_empty () co

int pop (); void push (int);

protected : static const int N int tab [N]; int top;};

#endif#endif

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s;

while (!s.is_full() && (cin >> c) ) s.push (c) ; while (!s.is_empty() ) cout << s.pop();}

The basic Stack

class :

utilization

I. Guided tour and basic concepts 12/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack (); // (default) constructor

bool is_full () con bool is_empty () co

int pop (); void push (int);

protected : static const int N int tab [N]; int top;};

#endif#endif

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s;

while (!s.is_full() && (cin >> c) ) s.push (c) ; while (!s.is_empty() ) cout << s.pop();}

The stack is automatically

created

The basic Stack

class :

utilization

I. Guided tour and basic concepts 13/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack (); // (default) constructor

bool is_full () con bool is_empty () co

int pop (); void push (int);

protected : static const int N int tab [N]; int top;};

#endif#endif

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s;

while (!s.is_full() && (cin >> c) ) s.push (c) ; while (!s.is_empty() ) cout << s.pop();}

Readoperator

The basic Stack

class :

utilization

I. Guided tour and basic concepts 14/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack (); // (default) constructor

bool is_full () con bool is_empty () co

int pop (); void push (int);

protected : static const int N int tab [N]; int top;};

#endif#endif

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s;

while (!s.is_full() && (cin >> c) ) s.push (c) ; while (!s.is_empty() ) cout << s.pop();} Write

operator

The basic Stack

class :

utilization

I. Guided tour and basic concepts 15/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

int pop (); void push (int);

protected : static const int N = 10; int tab [N]; int top;};

#endif#endif

#include "stack.h"#include "stack.h"

Stack::Stack() : top(0) { }

bool Stack::is_full() const { return top >= N; }

bool Stack::is_empty() const { return top <= 0; }

int Stack::pop() { return tab [--top]; }

void Stack::push (int c) { tab [top++] = c; }

The basic Stack

class :

implementation

I. Guided tour and basic concepts 16/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack (); //

bool is_full () con bool is_empty () co

int pop (); void push (int);

protected : static const int N = 10; int tab [N]; int top;

Stack::Stack () : top(0) { }

bool Stack::is_full (bool Stack ::is_empt

#include <iostream>#include <iostream>using namespace std;#include "stack.h" #include "stack.h"

main () { int c; Stack s; // s created in C++// s created in C++ while (!s.is_full() && (cin >> c) ) s.push (c) ; while (!s.is_empty() ) cout << s.pop();}

The basic Stack

class :

use, again

in Java, s not created

I. Guided tour and basic concepts 17/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack (); //

bool is_full () const; bool is_empty () const;

int pop (); void push (int);

Stack::Stack () : top(0) { }

bool Stack::is_full ()bool Stack ::is_empty

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s;

while (!s.is_full() && (cin >> c) ) s.push (c) ; while (!s.is_empty () ) cout << s.pop ();}

// s.top == 0// s.top == 0

in C++

The basic Stack

class :

use, again

I. Guided tour and basic concepts 18/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack (); //

bool is_full () const; bool is_empty () const;

int pop (); void push (int);

protected : static const int N = 10; int tab [N]; int top;};

#endif#endif

compilation of theStack class

#include "stack.h"#include "stack.h"

Stack::Stack () : top(0) { }

bool Stack::is_full () const { return top >= N; }

bool Stack::is_empty () const { return top <= 0; }

int Stack::pop () { return tab [--top]; }

void Stack::push (int c) { tab [top++] = c; }

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s;

while (!s.is_full() && (cin >> c) ) s.push (c) ; while (!s.is_empty () ) cout << s.pop ();}

g++ -o essai stack.cc demo.ccg++ -o essai stack.cc demo.cc

or (better)

g++ -c stack.ccg++ -c stack.ccg++ -c demo.ccg++ -c demo.ccg++ -o essai stack.o demo.og++ -o essai stack.o demo.o

I. Guided tour and basic concepts 19/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

void push (int); int pop ();

protected : static const int N = 10; int tab [N]; int top;};

#endif#endif

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s; while (cin >> c) s.pushs.push (c);

for (int i = 0; i < 10; ++i) cout << s.pops.pop();}

The stack must

not be full

If more than10 numbers ?

Is the Stack

class robust ?

I. Guided tour and basic concepts 20/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

void push (int); int pop ();

protected : static const int N = 10; int tab [N]; int top;};

#endif#endif

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s; while (cin >> c) s.pushs.push (c);

for (int i = 0; i < 10; ++i) cout << s.pops.pop();}

The stack must

not be empty

If less then10 numbers ?

Is the Stack

class robust ?

I. Guided tour and basic concepts 21/68OOP in C++ © JacquesFarré UNS 2012

A safer Stack class

The Stack class does not anticipate misuses of its operations

Stack must guarantee that– it is not full before pushing a new value– it is not empty before popping a value

Must warn the user that the operation has not been done

We shall use exceptions

I. Guided tour and basic concepts 22/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

class Stack { public : Stack ();

bool is_full () const; bool is_empty () const; int pop (); void push (int);

class Full {}; class Empty {};

protected : static const int N = 10; int tab [N]; int top;};

#endif#endif

Stack::Stack () : top(0) { }

bool Stack::is_full () const { return top >= N; }

bool Stack::is_empty () const { return top <= 0; }

int Stack::pop () { if (top <= 0) throw Empty(); return tab [--top];}

void Stack::push (int c) { if (top >= N) throw Full(); tab [top++] = c;}

A safer Stack classspecification & implementation

I. Guided tour and basic concepts 23/68OOP in C++ © JacquesFarré UNS 2012

class Stack { public : Stack (); bool is_full () const; bool is_empty () const; int pop (); void push (int);

clas clas

protec stat int int };

Stack::Stack () {}

bool Stack::is_fulbool Stack::is_emp

int Stack:: if (top <= 0) th return tab}

void Stack::push (

if (top >= N) th tab [top++] = c;}

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

main () { int c; Stack s; try { while (cin >> c) s.push (c); for (int i = 1; i < 10; ++i) cout << s.pop (); } catch (Stack::Empty& x) { … } catch (Stack::Full& x) { … }}

If more than10 nombers

A safer Stack class :

exceptions handling

I. Guided tour and basic concepts 24/68OOP in C++ © JacquesFarré UNS 2012

class Stack { public : Stack (); bool is_full () const; bool is_empty () const; int pop (); void push (int);

class Empty { }; class Full { };

Stack::Stack () : top

bool Stack::is_full (bool Stack::is_empty

void Stack::push (int

if (top >= N) throw tab [top++] = c;}

#include <iostream>#include <iostream>using namespace std;#include "stack.h"#include "stack.h"

void foo () { int c; Stack s; while (cin >> c) s.push (c);}

main () { try { foo (); } catch (Stack::Full& x) { // do something }}

A safer Stack class :

exceptions handling

I. Guided tour and basic concepts 25/68OOP in C++ © JacquesFarré UNS 2012

Stack as a template (generic) class

Basically, a stack of 20 character strings has the same behaviour that a stack of 10 integers

Thus, we can define a model (template) valid for all stacks

I. Guided tour and basic concepts 26/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

#endif#endif

The template Stack class

elements type

max number of elements

I. Guided tour and basic concepts 27/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

#endif#endif

#include "stack.h"#include "stack.h"

template <typename ELEM, int SIZE>Stack<ELEM, SIZE>::Stack():top(0) {}

template <typename E, int S> bool Stack<E, S>::is_full () const { return top >= S;}template <typename E, int S> bool Stack<E, S>::is_empty () const { return top <= 0;}

template <typename E, int S> E Stack<E, S>::pop () { if (top <= 0) throw Empty (); return tab [--top];}template <typename E, int S> void Stack<E, S>::push (E c) { if (top >= S) throw Full (); tab [top++] = c;}

template parameter names can be changed as long as they remain consistent

The template Stack class

I. Guided tour and basic concepts 28/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () con bool is_empty () co

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

#endif#endif

#include <iostream>#include <iostream>#include <string>#include <string>using namespace std;

#include #include "stack.h""stack.h"

const int max = 10;

main () { int c; Stack<int, 100> si; while (cin >> c && !si.is_full() ) si.push (c);}

#include ”stack.cc” // with g++

It makes no sens to compile a template if its parameters are not known ⇒ g++ -o essai demo.cc

The template Stack class

I. Guided tour and basic concepts 29/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

#include ”stack.cc”#include ”stack.cc”#endif#endif

#include <iostream>#include <iostream>#include <string>#include <string>using namespace std;

#include #include "stack.h""stack.h"

const int max = 10;

main () { int c; Stack<int, 100> si;

Stack<string, 2 * max + 1> sc; string st = “hello”; sc.push (st); sc.push (“world”);

Stack< Stack<int, 100>, 5> ssi; ssi.push (si);}

anyconsta

ntexpres

sion

any type

really any type

The template Stack class

I. Guided tour and basic concepts 30/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

#include ”stack.cc#include ”stack.cc””#endif#endif

#include <iostream>#include <iostream>#include <string>#include <string>using namespace std;

#include #include "stack.h""stack.h"

main () { typedef Stack<int, 100> PileEntiers;

PileEntiers si;

Stack<PileEntiers, 5> ssi; ssi.push (si);}

The template Stack class

in order to make types more readable

I. Guided tour and basic concepts 31/68OOP in C++ © JacquesFarré UNS 2012

Specialization of the Stack class

How to add new functionnalities to the stack without modifying/editing its code ?

– For example, in order to access elements in the middle of the stack st, we want to be able to write int bottom = st[0];

We define a sub-type XStack of Stack : class derivation (inheritance)

Principle of substituabily :– Wherever a Stack was used, we can use

instead an XStack

I. Guided tour and basic concepts 32/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

#endif#endif

#ifndef _XSTACK_H#ifndef _XSTACK_H#define _XSTACK_H#define _XSTACK_H

#include "stack.h" #include "stack.h"

template <typename ELEM, int SIZE>class XStack : public Stack<ELEM, SIZE> { public : class BadIndex { };

int height () const { return top; }

ELEM get (int x) const { if (x < 0 || x >= top) throw BadIndex(); return tab [x]; } };

#endif#endif

Specialization of the Stack classthe XStack class

On this example, no need for an xstack.cc file, since all methods

have their body in the .h

I. Guided tour and basic concepts 33/68OOP in C++ © JacquesFarré UNS 2012

#ifndef _STACK_H#ifndef _STACK_H#define _STACK_H#define _STACK_H

template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

#endif#endif

#ifndef _XSTACK_H#ifndef _XSTACK_H#define _XSTACK_H#define _XSTACK_H

#include "stack.h"#include "stack.h"

template <typename ELEM, int SIZE>class XStack : public Stack<ELEM, SIZE> { public : class BadIndex { };

int height () const { return top; }

get ELEM operator[] (int x) const { if (x < 0 || x >= top) throw BadIndex(); return tab [x]; } };

#endif#endif

An operator method

Specialization of the Stack classthe XStack class

I. Guided tour and basic concepts 34/68OOP in C++ © JacquesFarré UNS 2012

… template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_fullis_full () c bool is_empty ()

ELEM pop (); void pushpush (

class Empty class Full

protected : ELEM tab [S int top;};

...template <typename ELEM, int SIZE>class XStack : public Stack<ELEM, SIZE> { public : class BadIndex { };

int height () const { return top; }

ELEM operator[] (int x) const {

#include <iostream>#include <iostream>using namespace std;#include "xstack.h"#include "xstack.h"

main () { int c; XStack<int, 10> xs; while (cin && !xs.is_full() ) { cin >> c; xs.push (c); } for (int i = 0; i < xs.height (); ++i) cout << xs[i]; }

// xs.operator[] (i)

Specialization of the Stack classthe XStack class

I. Guided tour and basic concepts 35/68OOP in C++ © JacquesFarré UNS 2012

… template <typename ELEM, int SIZE>class Stack { public : Stack ();

bool is_full () const; bool is_empty () const;

ELEM pop (); void push (ELEM);

class Empty { }; class Full { };

protected : ELEM tab [SIZE]; int top;};

...template <typename ELEM, int SIZE>class XStack : public Stack<ELEM, SIZE> { public : class BadIndex { };

int height () const { return top; }

ELEM operator[] (int x) const {

#include <iostream.h>#include <iostream.h>using namespace std;#include "xstack.h"#include "xstack.h"

main () { int c; XStack<int, 10> xs; while (!xs.is_full ()) { cin >> c; x.push (c); } Stack<int, 10> s = xs; for (int i = 0; i < 10; ++i) cout << s [i];}

ss is not an

XStackXStack

Specialization of the Stack classthe XStack class

I. Guided tour and basic concepts 36/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts of programming languages

Types and values Objects (also said variables, instances …) References to objects Pointers Value semantics and reference semantics Functions and operators Static vs dynamic

I. Guided tour and basic concepts 37/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : types

A type defines a set of values and a set of operations on these values; examples :

– Real numbers (primitives types)• values : a machine dependant subset of real

numbers• operations : sum, product …

– A displayable circle (user-defined type)• values : tuple (radius × center × color) where

– center is an user-defined type : pair (x × y)– color is a string (class of the library)

• operations : move_to, change_color …

I. Guided tour and basic concepts 38/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : classes and types

A class is an abstract data type, defined by the user or existing in some library

In general, programming languages have

– primitives types (for numbers, logics …)– mechanisms for defining new types :

arrays, pointers, structures, classes... Orthogonality : when all types can be

used in the same manner

I. Guided tour and basic concepts 39/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : values & objects

Any value belongs to a type :– An object of a given type contains a value

of this type : float r = 15.3, q = r :

• r references (denotes) an object that contains 15.3

• q references another object which (at that time) contains the same value

rr 15.315.3 15.315.3qq

I. Guided tour and basic concepts 40/68OOP in C++ © JacquesFarré UNS 2012

Primitives types of C++

Primitives types and values (like in C) : – Signed and unsigned integers (char, short, int, long) :’a’, -5, 0xFFFF, 07777, 18L, -18L, 18UL …

– reals (float, double, et long double) :3a.14, 5E+3, 3.14f …

– logics (bool) : false, true– enumerateds :

enum State = {on, off};enum Time = {s=1, m=60, h=3600};

I. Guided tour and basic concepts 41/68OOP in C++ © JacquesFarré UNS 2012

The type modifier const

Given a type T– const T : object with a value that cannot be

modified• The value must be given at the object

creationconst double pi = 3.1416;

• The object cannot be modified• The value can be a non constant expression • Assignment pi = … illegale (in fact, any use

of pi which would modify its value is illegal)

pi 3.1416const

I. Guided tour and basic concepts 42/68OOP in C++ © JacquesFarré UNS 2012

The reference type

Given a type TT& : references an object of type Tint i = 3; int k = i; int& j = i;

i

3 k

3

double& rpi = pi; illegal since pi could be

modified through rpi idem in the following case void Foo (double& d) {…} … Foo (pi);

It is not allowed to create

a non-const reference from a const reference

Type referenceis mainly used for

function parameters and results

pi 3.1416const

rpi

j dénote le même objet que i

j

I. Guided tour and basic concepts 43/68OOP in C++ © JacquesFarré UNS 2012

The const reference type

•Given a type T const T& : reference on a constant T :const double& rpi = pi;

•The object on which the reference is made is not necessarily a constant

double r; const double& rr = r;

rr does not denote a constant, but the object r cannot be modified through rr

pi 3.1416

const

rpi const

r 0.5

rr const

It is allowed to create

a const reference from

a non-const référence

I. Guided tour and basic concepts 44/68OOP in C++ © JacquesFarré UNS 2012

The pointer type

Given a type T T* : pointer to an objet of type T – int i; int *p = &i;

• value of p : it is a reference !• *p denotes the same object as i• p = 0 → p points to nothing

– double* rpi = &pi;• illegal since pi could be modified through *rpi• idem in the following case :void Foo (double* d) {…} … Foo (&pi);

i

*p

p

I. Guided tour and basic concepts 45/68OOP in C++ © JacquesFarré UNS 2012

The pointer type to const

const T* : pointer to a constant object of type T

const double* ppi = &pi;*ppi = … illegal

(later, ppi may point to another object of type const double : ppi = pr legal)

The other object is not necessarily constantdouble r;const double* pr = &r;

*pr does not denote pas a constant :

the object may be modified thru r, but not thru *pr

r

pr const

pi 3.1416const

ppi const

I. Guided tour and basic concepts 46/68OOP in C++ © JacquesFarré UNS 2012

The constant pointer type

T* const : constant pointeur to a non constant object of type T

int* const j = &i;

j = … illegal : j will always points to the objet denoted by i

*j = … legal : j does not point to a constant

const T* const : constant pointer to a constant objet of type T const double* const cpi = &pi;

i 3.1416

const j

pi 3.1416

constcpi

const

const

I. Guided tour and basic concepts 47/68OOP in C++ © JacquesFarré UNS 2012

a C array is notis not

a class

!

The array type (as in C)

Given a type T– T[…] : array (of fixed size) of objects of type Tchar name [10]; double matrix [20][30];Stack stackArray [5];

double [20] v; not legal – Array size : any constant integer expression– access to array elements : matrix[i][j];

• Indexes start at 0• No check on the index value• Better use the vector class of the STL

I. Guided tour and basic concepts 48/68OOP in C++ © JacquesFarré UNS 2012

Pointers and arrays in C

double v[10]; double* p = v;

double m[3][10];double* q[3];

0 1 2 3 4 5 6 7 8 9

p

v

v[3]p[3] P + 3

→ p[3] ≡ *(p + 3)

q

m 012

0 1 2 3 4 5 6 7 8 9

I. Guided tour and basic concepts 49/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : values & objects

Class Point { Class Circle { … … double x, y; double radius;}; Point center;

string color;};

The center of the circlebelongs to the circle :nobody except the circlecan change the coordinates of the center

Circle Point1111

Diagramme UMLDiagramme UML

I. Guided tour and basic concepts 50/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : values & objects

A value can contain other valuesCircle c (7, Point (25, 30), ”blue”);Circle d (5, Point (12, 17), ”red”);

c references an object of type Circle that contains la valeur (7, (25, 30), ”blue”)

ddradius

center

color ”red”

x y

1217

5ccradius

center

color ”blue”

x y

2530

7

I. Guided tour and basic concepts 51/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts de base : reference semantics

Value semantics (C++) : assignment means copy of object value

Circle c, d; … d = c; gives

ccradius

center

color ”blue”

x y

2530

7 ddradius

center

color ”red” “blue”

x y

12 2517 30

5 7

I. Guided tour and basic concepts 52/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts de base : reference semantics

Reference semantics (Java) : assignment means sharing of references

Circle c, d; … d = c; gives

in C++, same behaviour using pointersCircle *c, *d; … d = c;

ccradius

center

color ”blue”

x y

2530

7 ddradius

center

color ”red”

x y

1217

5

I. Guided tour and basic concepts 53/68OOP in C++ © JacquesFarré UNS 2012

Class Point { Class Circle { … … double x, y; double radius;}; Point *center;

string color;};

The center can be sharedby several circles, each onebeing able to take another center. Furthermore, the center coordinates can be changed by other than the circles

Basic concepts : value and reference semantics

Circle Point11NN

UML diagramm UML diagramm

I. Guided tour and basic concepts 54/68OOP in C++ © JacquesFarré UNS 2012

An object can thus contain references on other objects through pointers :

Point p (25, 30);Circle2 c (7, &p, ”blue”);

Circle2 d (5, &p, ”red”);radiuscentercolor

7

”blue”cc

pp

Basic concepts : value and reference semantics

x y

25

30radiuscentercolor

5

”red” dd

I. Guided tour and basic concepts 55/68OOP in C++ © JacquesFarré UNS 2012

Class Point { Class Circle { … … double x, y; double radius;}; Point& center;

string color;};

The center can beshared by severalcircles, which cannottake another center

Basic concepts : value and reference semantics

Circle Point11NN

UML Diagramm UML Diagramm

I. Guided tour and basic concepts 56/68OOP in C++ © JacquesFarré UNS 2012

An object can thus contain references toother objects Point p (25, 30);

Circle2 c (7, p, ”blue”);Circle2 d (5, P, ”red”);

radiuscentercolor

7

”blue”cc

pp

Basic concepts : value and reference semantics

x y

25

30radiuscentercolor

5

”red” dd

I. Guided tour and basic concepts 57/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : functions and methods

A function definines a computation on its parameters ; it may return a result

– A function is not binded to an object (unlike methods)

– Function/method declaration = signature (ou function type, or prototype) : parameters and result type (parameter names not mandatory) : void cumulate (int&, int);Date& today (const Calendar&);

I. Guided tour and basic concepts 58/68OOP in C++ © JacquesFarré UNS 2012

– Function definition = prototype AND function bodydouble square (double a) { return a * a; }

– in C (as in many other languages), a function must be declared or defined before being called :double square (double); // declaration,. . . // not definition

void CircleArea (double r) { // definition const double pi = 3.1416; return pi * square (r);}

Basic concepts : functions

I. Guided tour and basic concepts 59/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : parameter passing modes

The function signature describes how parameters will be given to the function

void cumulate (int& c, int v) {void cumulate (int& c, int v) { c += square (v); c += square (v);}}

int SquareSum (int n) {int SquareSum (int n) { int s = 0; int s = 0; for (int i = 1; i < n; ++i) for (int i = 1; i < n; ++i) cumulate (s, i); cumulate (s, i); return s; return s;

}}

11ii

ss

vvcc

0 0

by valueby valueby referenceby reference

11

cop

y

0 10 1

I. Guided tour and basic concepts 60/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : default parameters

In C++, a function signature (or a method signature) can contain parameters with default value

void F (double, int = 0, bool = true);…F (3.14, 5, false);F (1.5, 2); // F (1.5, 2, true);F (3); // F (3, 0, true);

The default parameters can only be at the end of the parameter liste :

void F (double = 0.0, int, bool = true);not allowed

I. Guided tour and basic concepts 61/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : template functions

A function can be generic (this is then a template for a set of functions) :

template <type T>T max (T a, T b) { return a > b ? a : b; }

– Assumes that operator > is defined for type T Implicit instanciation of type T

– int m = max (2, 3); // int max(int, int)float r = max (3.14, 2.27); // float max(float, float)

Explicit instanciation of type T– float x = max<float> (2, 3.14);

Methods of a template class are also template

I. Guided tour and basic concepts 62/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : functionsand operators

Operators are functions : – a - b is a way to write sub(a,b)

or, in C++, operator-(a,b)

Signatures of a function-opérator ⊗ :– Binary operators : T operator⊗ (Tl,Tr)– Unary operators : T operator⊗ (To)– Operand types and result type are not

necessarily the same

I. Guided tour and basic concepts 63/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : methodsand operators

Operators can also be methods : – a - b is another way to write a.sub(b)

or, in C++, a.operator-(b)

Signatures of a method-operator ⊗ :– Binary operators : T operator⊗ (Tr)– Unary operators : T operator⊗ ()– Types of operands and of result are not

necessarily the same

I. Guided tour and basic concepts 64/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts : static versus dynamic

Do not confuse compilation and execution of a program

– Static : what is done at compile time– Dynamic: what is done at execution time

Examples :– Variables with static allocation, constant

expressions, size of a variable, type analysis, function code expansion …

– Dynamic allocation of memory, evaluation of expressions, computation of the address of an array element, function call …

I. Guided tour and basic concepts 65/68OOP in C++ © JacquesFarré UNS 2012

Basic concepts de base : steps for the compilation of a program

foo.hfoo.hbar.ccbar.cc

compilateur C++

bar.hbar.h

préprocesseur C

foo.ccfoo.cc

bar.obar.o foo.ofoo.o

C++ linkerC++ linkerlibrary-1library-1

library-Nlibrary-N

foobarfoobar

g++ -c bar.cc …g++ -c bar.cc …

g++ -o foobar bar.o foo.o …g++ -o foobar bar.o foo.o …

préprocesseur C

compilateur C++

g++ -c foo.cc …g++ -c foo.cc …

I. Guided tour and basic concepts 66/68OOP in C++ © JacquesFarré UNS 2012

C++ & Java

Similar syntaxes, but very important differences in semantics

● In C++:● value and reference semantics for any types (in Java, value

semantics for primitives types, reference semantics for object)● genericity (templates) → maximum static typing ● global variables et functions (not only attributes and methods)● Operator overloading (methods and functions)● Multiple inheritance ● User-defined conversions

● But very limited resources for the organization of large software (only the C preprocessor)

● And (good or bad ?) no garbage collection by default

I. Guided tour and basic concepts 67/68OOP in C++ © JacquesFarré UNS 2012

C++ & Java

C++ designed– With attention to software engineering issues– With a goal of efficiency– To remain compatible with C– As a compromise between theoretical

aspects and practical constraints

These goals are not fully achieved– Language difficult to master

• Easy to fall in a C trapC++ is really complex

– Lack of standard libraries (for graphics, distributed and concurrent objects, persistency…) but there exists the BOOST library (soon in the ISO standard)

Excuse me, boss,Excuse me, boss,I skipped classesI skipped classes

of C++of C++

I. Guided tour and basic concepts 68/68OOP in C++ © JacquesFarré UNS 2012

End part I