chapter 5 classes and objects §5.1 specifying a class §5.2 defining member functions §5.3 memory...

27
Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from Functions §5.5 Friendship

Upload: abigayle-robertson

Post on 13-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Chapter 5 Classes and Objects

§5.1 Specifying a class§5.2 Defining Member Functions§5.3 Memory Allocation and Static Members§5.4 Passing Objects to/from Functions§5.5 Friendship

Page 2: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

2

§ 5.1 Specifying a Class

Object(对象) Abstraction of entities State + Behavior

Class (类) A user-defined data type that declare objects Variables + Functions

radius,getArea()

Page 3: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Declaring a Class

3

class class_name {private: variable declarations; function declarations;public: variable declarations; function declarations;};

class class_name {private: variable declarations; function declarations;public: variable declarations; function declarations;};

class item{      int number;      float cost;    public:     void getdata(int a, float b);    //function declaration     void putdata(void);};

No initial value in declaration!

The following members are accessible outside the class

The following members are NOT accessible outside the class

private:

Page 4: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

4

Creating Objects

The syntax to create an object

ClassName variableName;

For example,

item x;

item x, y, z;

Memory for x is createdMemory for x is created

Data type vs. VariableClass vs. Object

Data type vs. VariableClass vs. Object

Page 5: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

5

Accessing Objects

To access the members of a class/object Data fields and functions

objectName.dataField

--references a data field in the object.

objectName.function(arguments)

--invokes a function on the object.

Page 6: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Data hiding in class

6

class xyz{     int x;     int y; public:     int z;};

int main(){ xyz p; p.x = 0; //error, x is private p.z =10; //OK, z is public}

Page 7: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Private Member Functions

Normally: data in private; functions in public Some functions in private sections

Can only be called by member function of its class To protect data from modifications by outsiders

7

class sample {

int m; void read(void);

public: void update(void); void write(void);

};

Page 8: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

8

Getter and Setter

For users/clients of a class to retrieve and modify a data field encapsulated by “private”

Getter/Accessor A function usually named getXxx:

Setter/Mutator A function usually named setXxx, e.g.:

returnType getPropertyName()returnType getPropertyName()

bool isPropertyName()bool isPropertyName()

void setPropertyName(dataType propertyValue)void setPropertyName(dataType propertyValue)

Page 9: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

9

A Simple Circle Class

To demonstrate creating objects, accessing data, and using functions

TestCircleTestCircle RunRun

Page 10: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Pointers to Members

A class member pointer can be declared using the operator ::* with the class name.

For example:

10

class A { private:

int m; public:

void show();};

int A::* ip = &A::m;

Page 11: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

§ 5.2 Defining Member Functions

11

return-type class-name :: function-name (parameters){ Function body}

return-type class-name :: function-name (parameters){ Function body}

Identity labelScope resolution operation

Page 12: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

12

Inline Declaration

A member function can be implemented inside a class declaration automatically an inline function

class A {

public:

A() {

// do something;

}

double f1() {

// return a number

}

double f2();

};

Inline functionInline functionInline functionInline function

Regular functionRegular function

double A::f2(){ // return a number}

double A::f2(){ // return a number}

inline double A::f2()

Inline functionInline function

Page 13: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

13

Separating Declaration from Implementation

Similar to the definition of function Declaration(声明) :

In classname.h file, conventionally Simply lists all the data fields, constructor prototypes,

and the function prototypes. Implementation(实现) :

In classname .cpp file, conventionally Implements the constructors and functions.

Circle.hCircle.h RunRunCircle.cppCircle.cpp

Page 14: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

#include <iostream> using namespace std; class set{

int m, n; public:

void display(void);int largest(void);

}; int set::largest(void){

if(m<=n) return m; else return n;

} void set::display(){

cout<<largest()<<"\n"; }

Nesting of Member Functions

14

A member function can be called by another member function of the same class

•Via function name directly (no object name)

Page 15: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

§ 5.3 Memory Allocation and Static Members

15

Memory of member functions -- Common for all objects -- Created/Allocated when defined

Memory of member functions -- Common for all objects -- Created/Allocated when defined

Memory of member variables -- specific to an object -- Created/Allocated when object created

Memory of member variables -- specific to an object -- Created/Allocated when object created

Member function1Member function1

Member function2Member function2

Object1: Member variable1Object1: Member variable1

Object1: Member variable2Object1: Member variable2

Object1: Member variable1Object1: Member variable1

Object1: Member variable2Object1: Member variable2

Page 16: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

16

Array of Objects

employee manager[3];

Circle circleArray[3] = {Circle(3), Circle(4), Circle(5)};

RunRunTotalAreaTotalArea

namename

ageageManager[0]Manager[0]

namename

ageageManager[1]Manager[1]

namename

ageageManager[2]Manager[2]

Page 17: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Static/Class Variables (静态 /类变量) Data fields shared by all the objects of the same class Stored in static memory region To declare:

static type var_name;//In declaration To initialize:

type ClassName::var_name = 0;

//re-declare it with initial value in implementation To access/reference:

(ClassName::)var_name…

17

Page 18: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Static Functions

Member function that can be called without creating an instance of the class

To declare:

static type functionName(parameters){} “static” appears in declaration file

To call:

ClassName::functionName(arguments);

18

Page 19: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Example of Static Members

19

Circle -radius: double

-numberOfObjects: int

+getNumberOfObjects(): int

+getArea(): double

1

radius

circle1 radius = 1 numberOfObjects = 2

Instantiate (实例化)

Memory

2

5

radius

numberOfObjects

UML Notation: underline: static variables or functions

circle2 radius = 5 numberOfObjects = 2

RunRun

TestCircle5.cppTestCircle5.cppCircle5.hCircle5.h Circle5.cppCircle5.cpp

Page 20: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

20

§ 5.4 Passing Objects to/from Functions

You can pass objects by value or by reference/address.

RunRun

RunRunPassObjectByValuePassObjectByValue

PassObjectByReferencePassObjectByReference

RunRunPassObjectToPointerPassObjectToPointer

c: Circle

radius: 5.0

myCircle: Circle radius: 5.0

Copy myCircle to c

myCircle: Circle

radius: 5.0

c is an alias for myCircle

myCircle: Circle radius: 5.0

c:

address of myCircle

Page 21: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Returning Objects

Objects can be returned to caller Example:

21

class complex{ //x + iy form float x; float y;public: void input(float real, float imag) { x = real; y = imag;} friend complex sum(complex, complex); void show(){ cout << c.x << " + i" << c.y <<"\n"; }};

complex sum(complex c1, complex c2){ complex c3; c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return (c3);}

int main(){ complex A, B, C; A.input(3.1, 5,65); B.input(2.75, 1.2); C = sum(A, B); cout << "C = "; C.show();}

Friendship!Friendship!

Page 22: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

§5.5 Friendly Function/Class

Friends(友元 ): some special classes/functions that

can directly access the private members of a class.

Syntax:

22

class Name{ … friend class FriendName; friend type funcName(); …};

class Name{ … friend class FriendName; friend type funcName(); …};

Page 23: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Notes

Friends can be declared in either “public” or “private” part No difference.

All the member functions of a friend class are friend functions

The implementation of friend function can be put inside OR outside the definition of the class

23

Page 24: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Example of Friend Function

24

RunRunTestFriendFunctionTestFriendFunction

class Date { friend void p(); private: int year; int month; int day; }; void p() { Date date; date.year = 2000; cout << date.year; }

class Date { friend void p(); private: int year; int month; int day; }; void p() { Date date; date.year = 2000; cout << date.year; }

Page 25: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Example of Friend Class

25

RunRunTestFriendClassTestFriendClass

Date2 .hDate2 .h

class AccessDate { public: static void p() { Date birthDate; birthDate.year = 2000; cout << birthDate.year; } };

class AccessDate { public: static void p() { Date birthDate; birthDate.year = 2000; cout << birthDate.year; } };

class Date {

public:

friend class AccessDate;

private:

int year; int month; int day;

};

class Date {

public:

friend class AccessDate;

private:

int year; int month; int day;

};

Page 26: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Summary

Declaration of class Access control: public vs. private

Data hiding

Class member pointer Memory allocation Static members Object as parameter Object as returning value Friendly function/class

26

Page 27: Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from

Review Questions

Q5.1 Q5.7 Q5.8

27