37
Plab 2003 Lecture 4 1 C++ - Classes

Plab 2003 Lecture 41 C++ - Classes. Plab 2003 Lecture 42 Motivating Example Goal: Graphics package Handle drawing of different shapes Maintain list of

  • View
    222

  • Download
    1

Embed Size (px)

Citation preview

Plab 2003 Lecture 4 1

C++ - Classes

Plab 2003 Lecture 4 2

Motivating Example

Goal:

• Graphics package

• Handle drawing of different shapes

• Maintain list of shapes

Plab 2003 Lecture 4 3

Solution #1struct Shape {

enum { RECTANGLE, CIRCLE, TRIANGLE } type;double x, y;double height, width;

};

voiddraw( Shape const* shape ){

switch( shape->type ){

case RECTANGLE:…case CIRCLE:…

Plab 2003 Lecture 4 4

Solution #1 - Discussion

Pros:

• Simple, direct

Cons:

• Adding new shapes requires changing all procedures that deal with shape.

• Require fat interface in order to support all kinds of shapes.

• No type checking. Unsafe!

Plab 2003 Lecture 4 5

Solution #2

Allow to implement shape specific codestruct Shape {

double x, y;

double height, width;

void (*draw)( Shape const* );

};

void

draw( Shape const* shape )

{

(*shape->draw)(shape);

}

Plab 2003 Lecture 4 6

Solution #2Pros:• Extendable• Drawing method of each shape encapsulated• Efficient

Cons:• Require fat interface in order to support all

kinds of shapes.• Still no type checking. Unsafe!

Plab 2003 Lecture 4 7

Solution #3 – C++ classes

C++ Language provides tools that support object oriented programming.

Plab 2003 Lecture 4 8

Simple Class Definitionclass Counter {

public:

//function prototypes

Counter(); // Constructor

void increment(); // A method

int value() const; // Another method

private:

int m_count;

};

Plab 2003 Lecture 4 9

Class Implementation

Counter::Counter() { //fully qualified name m_count = 0;

}

void Counter::increment(){ m_count++;}

int Counter::value(){ return m_count;}

Plab 2003 Lecture 4 10

Using the classint main()

{

Counter cnt; // default constructor!

printf("Initial value = %d\n", cnt.value() );

cnt.increment();

printf("New value = %d\n", cnt.value() );

}

Plab 2003 Lecture 4 11

Class Basics: Access control

• Declare which parts of the class are accessible outside the class

class Counter {public: //designate a section! … // accessible from outside

private: //designate a section! … // private

};

Plab 2003 Lecture 4 12

Example

class Counter {

public:

Counter();

int value()const;

void increment();

int m_flag;

private:

int m_counter;

};

int main() {

Counter c;

// legal

int x = c.value();

int y = c.m_flag;

// illegal

c.m_counter = 2.0;

}

Plab 2003 Lecture 4 13

Class Basics: Constructors

• Initialize the class object upon construction

class Counter {public: Counter(); //default constructor Counter( int c ); //2 Counter( int c, int f ); //3

};…Counter a; // Calls default constructorCounter b(0); // Calls 2Counter c( 1, 2); // Calls 3

Plab 2003 Lecture 4 14

Default arguments in constructors/functions

In C++Counter::Counter( int c = 0, int f = 1){

}Note that now Counter has a default constructor!Counter::Counter( int c = 0, int f) //illegal{

}

Plab 2003 Lecture 4 15

Destructors

• Ensure propose “cleanup” when the object is destructed

• Use for freeing memory, notifying related objects.

• free resources. Files, Sockets…

Plab 2003 Lecture 4 16

Class Basics: Destructors

class Counter {

public:

Counter();

~Counter(); // destructor

private:

char* message;

};

Counter::Counter(){

message = (char*)malloc(1000);

}

Counter::~Counter(){

free(message);

}

int main(){Counter a;

if( … ){

Counter b;…

}…

}

Plab 2003 Lecture 4 17

Class – Memory Management

Representation of data structure list.

• C++ implementation of data structure

• Data members of IntList are protected using appropriate access control.

• Usage is more natural…

IntList L;

L.pushFront(6)

if( !L.isEmpty() )

x = L.popBack();

Plab 2003 Lecture 4 18

Class – Memory Management Cont

Consider this code

main(){

IntList L;…

}

What is the difference?

Compare to main()

{

IntList* L = (IntList*)malloc(

sizeof(IntList));

free(L)

}

Plab 2003 Lecture 4 19

IntList* L = (IntList*)malloc(sizeof(IntList));

• Does not call constructor!

• Internal data members are not initialized

free(L);

• Does not call destructor!

• Internal data members are not freed

Class – Memory Management Cont

Plab 2003 Lecture 4 20

new & delete - Operators

Special operators:• IntList* L = new IntList;

– allocate memory

– call constructor• delete L;

– call destructor

– free memory

Plab 2003 Lecture 4 21

New

new <type>;

• Allocate an object of type <type>

• Apply constructor to the new object

• Return a pointer to the new object

Can be used with any type:int *i = new int;

char** p = new (char *);

Plab 2003 Lecture 4 22

New & Constructorsclass Counter {

public:

Counter();

Counter( int c );

Counter( int c, int f);

};

Counter* cp;

cp = new Counter; // Calls

cp = new Counter(1); // Calls

cp = new Counter(1, 2); // Calls

Plab 2003 Lecture 4 23

New & arrays

To allocate arrays, use

int n = 4;

int* a = new int[10]; // array of 10 ints

IntList* b = new IntList[n];

// array of n IntLists

• Objects in allocated array must have an default constructor!

Plab 2003 Lecture 4 24

Delete & array

Special operation to delete arrays

int* a = new int[10];

int* b = new int[10];

delete [] a; // proper delete command

delete b; // error, undefined behavior!

Plab 2003 Lecture 4 25

Member Initialization

class Point { public: Point(int x, int y); ~Point(); int getX() const; int getY() const;private: int m_x, m_y;

};

Plab 2003 Lecture 4 26

#include "Point.h“

class Circle {public: Circle(int x, int y, double r); ~Circle(); // ...private: Point m_center; // ...};

Member Initialization Cont

Plab 2003 Lecture 4 27

#include "Circle.h“

Circle::Circle(int x, int y, double r) : m_center(x,y) { // ... }Circle::~Circle() { printf(“in ~Circle()");}

Member Initialization Cont

Won’t compile without

Plab 2003 Lecture 4 28

Member Initialization ContThe same syntax also works for primitive types

Point::Point(int x, int y) : m_x(x) , m_y(y) {

}safer thanPoint::Point(int x, int y) { m_x = x; m_y = y;}

Plab 2003 Lecture 4 29

Inheritance• The main ideas are similar to what you

already know from Java.

• C++ has no interfaces but it allows multiple inheritance

Plab 2003 Lecture 4 30

#include "Point.h“

class Circle : Point {public: Circle(int x, int y, double r);

~Circle(); // ...#include "Circle.h“

Circle::Circle(int x, int y, double r) : Point(x,y) { // ... }Circle::~Circle() { printf(“in ~Circle()");

}

Member Initialization

Won’t compile without

Plab 2003 Lecture 4 31

C-tor & D-tor order of execution• Constructor of the base class is the 1st to be

executed. Why?

• Then the members are constructed.

• Finally, the constructor of the class itself is executed.

• Destruction is done in the opposite order.

Plab 2003 Lecture 4 32

protected

Class members that should be accessible by subclasses are declared protected.

Plab 2003 Lecture 4 33

“this” pointer• A (constant) pointer to the instance for which

the member function was invoked.

• Example:

class List { List* next;public: bool on(List*); // ...};

bool List::on(List* p) { if (p==null) return false; for (List *q = this; q; q=q->next) if (q == p) return true; return false; }

Plab 2003 Lecture 4 34

inline functions

• A hint to a compiler to put function’s code inline, rather than perform a regular function call.

• Objective: improve performance of small, frequently used functions.

Plab 2003 Lecture 4 35

inline functions Cont

• Example:allocateNode() function in data

structures like Linked List or Binary Tree.

• A member function defined in class definition (i.e. the header file) is automatically considered to be inline.

• An inline function defined in .cpp file is not recognized in other source files.

Plab 2003 Lecture 4 36

Static class members

• These are class members

class X{ private: static int instances; public: X() { instances++; } ~X(); { instances--; } static int getInstances() const { return instances; }};

Plab 2003 Lecture 4 37

Static class members

Example of using a static function:

X x1;// ...X x2;// ...printf(“%d\n”, X::getInstances());

Somewhere (but only in one place!) the instances variable should be defined://C++ use qualified namesint X::instances = 0; In Java

declaration and defintion were in the same place