56
C++ AND C ID1218 Lecture 09 2009-11-25 Christian Schulte [email protected] Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

C++ AND C ID1218 Lecture 092009-11-25 Christian Schulte [email protected] Software and Computer Systems School of Information and Communication Technology

  • View
    216

  • Download
    1

Embed Size (px)

Citation preview

C++ AND C

ID1218 Lecture 09 2009-11-25

Christian [email protected]

Software and Computer SystemsSchool of Information and Communication

TechnologyKTH – Royal Institute of Technology

Stockholm, Sweden

L09, 2009-11-25ID1218, Christian Schulte

2

Overview

Objects Inheritance Templates Operators C

L09, 2009-11-25ID1218, Christian Schulte

3

Reading Suggestions

All of you thorough reading of chapters 4, 6, 12

Objects and Classes

L09, 2009-11-25

4

ID1218, Christian Schulte

L09, 2009-11-25ID1218, Christian Schulte

5

An Integer Cell

class IntCell {private: int x;public: IntCell(int y=0) { x=y; } int get() { return x; } void set(int y) { x=y; }};

L09, 2009-11-25ID1218, Christian Schulte

6

Accessors vs Mutators

Fundamental difference set: changes object state (mutator) get: does not change state (accessor)

In C++ accessors need to be declared const

int get() const { return x;}

compiler enforces that state is not changed well, can be controlled with const-cast…

L09, 2009-11-25ID1218, Christian Schulte

7

Initializer Lists

Rewrite constructor toIntCell(int y=0) : x(y) {}

after colon: comma separated list in order of declaration of members

Old version first initialize with default constructor for

member then assign value

New version only initialized

Matters for non primitive data members!

L09, 2009-11-25ID1218, Christian Schulte

8

Copying and Assignment

Copying is controlled by copy constructorIntCell(const IntCell& c) : x(c.x) {}

Assignment is controlled by assignment operatorIntCell& operator=(const IntCell& c) { if (this != &c) x=c.x; return *this;}

These are synthesized by compiler if missing required for resource management

L09, 2009-11-25ID1218, Christian Schulte

9

A Different IntCell

Maintain integer via pointerclass IntCell {private: int* x;

public: IntCell(int y=0) : x(new int) { *x = y; } …

} how to manage the allocated memory?

L09, 2009-11-25ID1218, Christian Schulte

10

Copy Constructor

IntCell(const IntCell& c) : x(new int) { *x = *c.x;}

Used for parameter passing Used for initialization (assume c is IntCell)

IntCell d(c);

L09, 2009-11-25ID1218, Christian Schulte

11

Assignment Operator

IntCell& operator=(const IntCell& c) {

if (this != &c) {

delete x; x = c.x;

}

return *this;

} Returns an IntCell to allow assignment

sequences

a = b = c;

L09, 2009-11-25ID1218, Christian Schulte

12

Destructor

~IntCell() {

delete x;

}

When object is deleted by delete (for heap allocated) by going out of scope (for automatically allocated)

destructor is invoked for resource management

L09, 2009-11-25ID1218, Christian Schulte

13

Default Constructor

A constructor with no arguments (or all arguments with default values)

automatically generated, if no constructors provided

Important for initializationIntCell c;

invokes the default constructor

Fine Points for Objects

L09, 2009-11-25

14

ID1218, Christian Schulte

L09, 2009-11-25ID1218, Christian Schulte

15

Friends

Grant access to class internalsclass ListNode { friend class IntQueue; …

Can be fine-grained: for functions for member functions

L09, 2009-11-25ID1218, Christian Schulte

16

Static Members

Static member is part of class, not of instance

maintain data that is shared among all instances of a class

Requires declaration and definition Declaration

use keyword static done in header

Definition use class name done in implementation

L09, 2009-11-25ID1218, Christian Schulte

17

Static Members: Header

class Tracked { private: static int noi; public: Tracked() { noi++; … } …};

L09, 2009-11-25ID1218, Christian Schulte

18

Static Members: Implementation Can be initialized

int Tracked::noi = 0;

L09, 2009-11-25ID1218, Christian Schulte

19

Namespaces

Organize multiple functions, classes, etc together

similar to Java package

namespace N { class C …}

L09, 2009-11-25ID1218, Christian Schulte

20

Using Namespaces

Inside the namespace, as alwaysC

Outside namespaceN::C

Convenience: make available single class using N::C; namespace using namespace N;

Reference to C in global namespace::C

L09, 2009-11-25ID1218, Christian Schulte

21

Incomplete Class Declaration Mutual recursive definitions common

through pointersclass A { … B* data; };class B { … A* data; };

Use incomplete class definitionclass B;class A { … B* data; };class B { … A* data; };

only limited use of incompletely declared class allowed

Inheritance

L09, 2009-11-25

22

ID1218, Christian Schulte

L09, 2009-11-25ID1218, Christian Schulte

23

Inheritance

Construct classes from other classes inherit members and member functions

Supports public and private inheritance public is normal behavior (as in Java)

Supports multiple inheritance inherit from multiple classes not discussed here

L09, 2009-11-25ID1218, Christian Schulte

24

Person Classclass Person {private: int _pn; const char* _n;public: Person(int pn, const char* n) : _pn(pn), _n(n) {} int pn() const { return _pn; } const char* name() const { return _n; }};

L09, 2009-11-25ID1218, Christian Schulte

25

Student Class

class Student : public Person {private: int _pts;public: Student(int pn, const char* n, int pts)

: Person(pn,n), _pts(pts) {} int pts() const { return _pts; }}

L09, 2009-11-25ID1218, Christian Schulte

26

Adding Printing

class Person { … void print(ostream& o = std::cout) const { o << name() << "(" << pn << ")"; }};

class Student { … void print(ostream& o = std::cout) const { Person::print(o); o << "[" << pts() << "]"; }};

L09, 2009-11-25ID1218, Christian Schulte

27

Example Persons…

Works okayPerson p(1234, "Alice");Student s(5678, "Bob", 12);p.print();s.print();std::cout << s.name() << std::endl;

L09, 2009-11-25ID1218, Christian Schulte

28

Things Going Wrong…

Which print gets called…Student s(1234, "Carl", 34);void printme(const Person& p)

{ p.print();}printme(s);

uses Person::print rather than Student::print

known as static dispatch: based on compile-time type of p

L09, 2009-11-25ID1218, Christian Schulte

29

Dynamic Dispatch

Use runtime type for finding member function

default behavior in Java in C++: mark member functions as virtual

Fix printing in base classclass Person { … virtual void print(ostream& o=std::cout)

const { …};

L09, 2009-11-25ID1218, Christian Schulte

30

Defaults with Inheritance

Copy constructor invokes copy constructor on base classes invokes copy constructor on newly added data

members Assignment operator

invokes assignment operator on base classes invokes assignment operator on newly added data

members Destructor

invokes destructors on newly added data members invokes destructors on base classes

L09, 2009-11-25ID1218, Christian Schulte

31

Explicit Implementation

class Student { … Student(const Student& s) : Person(s), _pts(s._pts) {} ~Student() { // Invokes ~Person() automatically! } Student& operator=(const Student& s) { if (this != &s) { Person::operator=(s); _pts = s._pts; } return *this; }};

L09, 2009-11-25ID1218, Christian Schulte

32

Virtual Destructor

Consider exampleStudent* s = new Student(3456,

"Deb", 2);Person* p = s;delete p;

uses static dispatch: destructor of Person! Must declare destructor virtual in

baseclassvirtual ~Person() {}

L09, 2009-11-25ID1218, Christian Schulte

33

Abstract Methods and Classes Member functions can be declared abstract in

base class declare as virtual declaration followed by = 0;

Base class for geometric shapeclass Shape { public: virtual double area() const =

0; …};

L09, 2009-11-25ID1218, Christian Schulte

34

A Rectangle Class

class Rect : public Shape { public: … virtual double area() const { return size*size; }}; Not longer abstract

abstract class contains at least one abstract method

only non-abstract classes allow instances!

L09, 2009-11-25ID1218, Christian Schulte

35

Type Conversions

Assume we know that p is a student, reallyPerson* p = new

Student(123,"Eva",2); Use dynamic castStudent* s = dynamic_cast<Student*>(p);

performs check and cast at runtime returns NULL, if not a Student

Templates

L09, 2009-11-25

36

ID1218, Christian Schulte

L09, 2009-11-25ID1218, Christian Schulte

37

Generic Programming

Common example: collections in Java all members are of type Object has limitations: primitive types (requires

boxing), requires casts checked at runtime, … fixed in Java 5

Supported in C++ by templates abstract over types and values applicable to functions, classes, and member

functions

L09, 2009-11-25ID1218, Christian Schulte

38

Integer List Class

class IntList { private: int h; IntList* t; public: IntList(int h0, IntList* t0)

: h(h0), t(t0) {} int head() const { return h; } …}; Does not depend on type of list elements!

L09, 2009-11-25ID1218, Christian Schulte

39

Generic List Class

template <typename E>class List { private: E h; List<E>* t; public: List(const E& h0, List<E>* t0)

: h(h0), t(t0) {} const E& head() const { return h; }

…};

L09, 2009-11-25ID1218, Christian Schulte

40

Using the Generic List Class

List of integersList<int>* il =

new List<int>(4,NULL); List of floats

List<float>* fl = new List<float>(4.0,NULL);

L09, 2009-11-25ID1218, Christian Schulte

41

Template Functions

template <typename T>void ex(T& x, T& y) { T t = x; x = y; y = t;} Use as follows

int x = 4; int y = 5;ex(x,y);

uses automatic resolution of types complicated process, in particular with overloading

Can be explicitex<int>(x,y);

L09, 2009-11-25ID1218, Christian Schulte

42

Compilation Model

Still most useful strategy put everything in the header file both declaration and definition compiler will produce code if needed

Other strategies available explicit instantiation in implementation

template class List<int>; export directive

Operator Overloading

L09, 2009-11-25

43

ID1218, Christian Schulte

L09, 2009-11-25ID1218, Christian Schulte

44

Operator Overloading

Many operators (+, []) can be overloaded in C++

useful for concise programs Different strategies for overloading

make operator member function make operator function

Details, see book: chapter 5

L09, 2009-11-25ID1218, Christian Schulte

45

Overloading Printing

Overload the output operator <<

std::ostream& operator<<(ostream& o, const Person& p) { p.print(o); return o;}

L09, 2009-11-25ID1218, Christian Schulte

46

Overloading Memory Management Memory management for class instances

defined by operatorsstatic void* operator new(size_t);static void operator delete(void*); where void* pointer to anything where size_t integer type for specifying size discussed later

Can be used to change memory allocation policy per class

C Programming

L09, 2009-11-25

47

ID1218, Christian Schulte

L09, 2009-11-25ID1218, Christian Schulte

48

Major Differences…

No classes use structs (see later)

No references use pointers

No overloading No templates No default parameters All local variable declarations must be at

beginning of function Memory management Libraries

L09, 2009-11-25ID1218, Christian Schulte

49

The Struct Type

Combine data into one structure

struct IntPair {

int x; int y;

}; Also available in C++, corresponds to

class IntPair {

public:

int x; int y;

};

L09, 2009-11-25ID1218, Christian Schulte

50

Preprocessor Macros

Conditional compilation Textual substitution

#define FOOVALUE 1 Macros

#define max(x,y) (x>y?x:y) unsafe! unsafe! things go wrong

b = max(a--,c--);

L09, 2009-11-25ID1218, Christian Schulte

51

C-Style Memory Management Can also be useful in C++ Headers required

in C:

#include <stdlib.h> in C++

#include <cstdlib>

L09, 2009-11-25ID1218, Christian Schulte

52

C-Style Memory Management Allocate n bytes from heap

void* malloc(size_t n); Free memory block p obtained by malloc

void free(void* p); Never mix new+delete with malloc+free

never use delete on malloc block and vice versa

L09, 2009-11-25ID1218, Christian Schulte

53

Allocating Memory

In order to allocate memory know the size in bytes sizeof cast to appropriate type static_cast

Allocate memory for array of integers with 10 elementsint* a = static_cast<int*>(

malloc(10*sizeof(int)); in C: instead of static_cast use (int*)

L09, 2009-11-25ID1218, Christian Schulte

54

Pitfall…

What is the difference betweenC* c = new C;

andC* c = static_cast<C*>(

malloc(sizeof(C)); no default constructor called! same difference for delete versus free: no

destructor called!

Summary

L09, 2009-11-25

55

ID1218, Christian Schulte

L09, 2009-11-25ID1218, Christian Schulte

56

Summary

Objects and classes constructors: default, copy assignment operator destructor virtual member functions and abstract classes

Templates generic classes and functions

C different memory management many features of C++ missing