44
Copyright 2006 Oxford Consulting, Ltd 1 February 2006 - 1 - C++ Class Members C++ Class Members Class Definition class Name { public: constructor(s) destructor function members data members protected: function members data members private: function members data members };

C++ Class Members

  • Upload
    margie

  • View
    35

  • Download
    2

Embed Size (px)

DESCRIPTION

C++ Class Members. Class Definition class Name { public: constructor(s) destructor function members data members protected: function members data members private: function members data members };. C++ Class Members. Class Definition - Data Members Data Members - PowerPoint PPT Presentation

Citation preview

Page 1: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 1 -

C++ Class MembersC++ Class Members

Class Definition

class Name{public:

constructor(s)destructorfunction membersdata members

protected:function membersdata members

private:function membersdata members

};

Page 2: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 2 -

C++ Class MembersC++ Class Members

Class Definition - Data Members

Data Members

It is important to note …..

Each class instance gets distinct copies of all data members

Page 3: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 3 -

C++ Class MembersC++ Class Members

Class Definition - Data Members

class MyClass{public:

MyClass() { myValue = 10; }int getMyValue () { return myValue;}int setMyValue (int aValue) { myValue = aValue;}

private:int myValue;

};

int main(void){

MyClass inst0, inst1;inst1.setMyValue(20);cout << inst0.getMyValue() << endl

<< inst1.getMyValue() << endl;return 0;

}

class MyClass{public:

MyClass() { myValue = 10; }int getMyValue () { return myValue;}int setMyValue (int aValue) { myValue = aValue;}

private:int myValue;

};

int main(void){

MyClass inst0, inst1;inst1.setMyValue(20);cout << inst0.getMyValue() << endl

<< inst1.getMyValue() << endl;return 0;

}

Page 4: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 4 -

C++ Class MembersC++ Class Members

Class Definition - Function Members

Function Members

Unlike data members

Only one instance of each function member exists for a

class

Unless the function is declared inline

Page 5: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 5 -

C++ Class MembersC++ Class Members

Class Definition - Function Members

Function Members

If only a single instance…..

How are data members which function manipulates

bound to the function instance?????

What is not shown

The member function has a hidden argument

The arg is a pointer to the object that was sent the message

Pointer is identified by the keyword this

Page 6: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 6 -

C++ Class MembersC++ Class Members

Class Definition - Function Members

Function Members

The this pointer Has type ClassType

Contains the address of the class instance through which the member function was invoked

Starting address is same as the address of the first variable in the class structure

Page 7: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 7 -

C++ Class MembersC++ Class Members

Class Definition - Function Members

Function Members

Every nonstatic function member has a pointer implicitly declared

ClassName * const this;

this is initialized to point to the object for which the member

function was invoked

Because this is declared const

It cannot be changed

Object pointed to can

Page 8: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 8 -

C++ Class MembersC++ Class Members

Class Definition - Function Members

Function Members

Since this is a pointer to the beginning of the class structure

One can select elements using pointer notation

this -> myElement

To refer to the entire instance…..

*this

return *this

Will produce a copy of the instance as the return value

Page 9: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 9 -

C++ Class MembersC++ Class Members

Class Definition - Function Membersclass Link{public:

void append (Link* aLink);

void setPrev (Link* aLink);private:

Link* next;

Link* prev;};

void Link :: append(Link* aLink){

next = aLink;

aLink -> setPrev(this);

return;}

Li Li+1

this

Next

Previous

Page 10: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 10 -

C++ Class MembersC++ Class Members

Managing Storage - Object Creation

When a C++ object is created 2 events occur……..

Storage is allocated for the object

The constructor is called to initialize the storage

Storage allocation occurs in several ways and at different times

Page 11: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 11 -

C++ Class MembersC++ Class Members

Managing Storage - Object Creation

Static Storage

Allocated when the program begins

Constant for the life of the program

Stack

Storage allocated on the stack when an execution point is

reached - Opening curly brace.

Released at the complementary execution point - closing curly

brace.

Heap - Free Store

Storage is dynamically allocated from the heap at runtime

Page 12: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 12 -

C++ Class MembersC++ Class Members

Managing Storage - Object Creation

Declaration

Introduces a name

Tells the compiler what the name means

Usually go into header files

Definition

Allocates storage for the name

Page 13: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 13 -

C++ Class MembersC++ Class Members

Managing Storage - Object CreationVariable

The compiler determines the variable size and generates space

If there is an initializing value, the value entered into that storage

Compile time storage usually allocated at the opening brace

Constructor not called until sequence point where object defined

Auto storage will be allocated on the stack

Function Compiler generates code and allocates storage to hold the code Storage for function has an address that can be produced using

Function name with no arg list Address of operator

Usually go into implementation files

Page 14: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 14 -

C++ Class MembersC++ Class Members

Managing Storage - LinkageLinkage

Describes storage to represent an identifier as seen by linker

Internal

Storage created for identifier for file being compiled

Name may be used in other files without conflict

External

Single piece of storage for all files being compiled

Accessed from other files by keyword extern

Variables defined outside functions

Inline function definitions default to external linkage

Automatic (local) Variables

Exist on the stack while function being called

Auto variables have no linkage

Page 15: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 15 -

C++ Class MembersC++ Class Members

Managing Storage - Inline Functions

Inline Functions

C++ permits specification of inline functions

Identified by keyword inline … the definition of function follows

syntax

inline type functionName (argsi) { body }

When inline definition encountered

No code generated

Code remembered and substituted for each function call

Page 16: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 16 -

C++ Class MembersC++ Class Members

Static Data Members

A class is a type not a data object

When an instance of a class is defined…..

The instance gets a copy of all data members

If data member declared static

Single copy

Shared by all instances of the class

Smalltalk

Pool variables

class M char astatic int b

m0char a

m1char a

m2char a

m3char a

int b

Page 17: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 17 -

C++ Class MembersC++ Class Members

Static Data Memberssyntax

Declaration

static type varName;

Definition

type ClassName :: varName < = value >

Static member exists even if no class instances exist

Remain in scope of class

Can only be accessed from outside if declared public

Page 18: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 18 -

C++ Class MembersC++ Class Members

Static Data Members Storage for a static variable

Must be explicitly reserved and initialized

Static can be declared within a class

Definition and initialization must occur outside Class

Can be only single definition

Static (nonclass) variables

Initialized to 0 by default

Static class variables

Cannot be initialized by the constructor

Page 19: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 19 -

C++ Class MembersC++ Class Members

Initializing Static Data Members...

class SimpleClass{public:

SimpleClass () {} SimpleClass (int aValue){myValue = aValue;}

// static char myChar = 'c'; This is illegalstatic char myChar;

private:static int myValue;

};

// Define and initialize the static variables

int SimpleClass::myValue = 10;char SimpleClass::myChar = 'a';

class SimpleClass{public:

SimpleClass () {} SimpleClass (int aValue){myValue = aValue;}

// static char myChar = 'c'; This is illegalstatic char myChar;

private:static int myValue;

};

// Define and initialize the static variables

int SimpleClass::myValue = 10;char SimpleClass::myChar = 'a';

Page 20: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 20 -

C++ Class MembersC++ Class Members

Static Data Members

Static Data Member

Can appear as a default arg to a member function

Non-static Data Member

Cannot appear as a default arg to a member function

Within a class body…..

int a;

static int b;

int f1 ( int myValue0 = a ); // illegal

int f2 ( int myValue1 = b ); // ok

Page 21: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 21 -

C++ Class MembersC++ Class Members

Static Data MembersA static data member can be an instance of the class of which it is a

member…..

A non-static can only point to an instance of it’s class.

Within a class body

class F1

{

public:

F1 *a; // ok

static F1 b; // ok

F1 c; // illegal

};

Page 22: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 22 -

C++ Class MembersC++ Class Members

Const Data MembersClass data members can be specified as const

Consequence

Storage always allocated and must be initialized at point of

definition

Initialization must occur in the constructor

Implemented via the initialization list

Storage not allocated until instance created…...

At that time, the const must be

Created

Initialized

Const variable persists for the lifetime of the instance

Page 23: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 23 -

C++ Class MembersC++ Class Members

Static Function MembersFunction members can be declared static

A static function has no this pointer

static function can access

Directly

static members

enums and typedefs

Indirectly

Regular members via . or -> through an explicit object

Page 24: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 24 -

C++ Class MembersC++ Class Members

Static Function Members

class SimpleClass

{

public:

//static int getMyNumber() {return myNumber;} requires an object

static int getMyNumber() { return myValue;}

static int getMyStuff(SimpleClass *myClass) {return myClass-

>myNumber;}

static int getMyVal() {return myValue;}

static char myChar;

char myLetter;

private:

static int myValue;

int myNumber;

};

int SimpleClass::myValue=10;

char SimpleClass::myChar = 'a';

class SimpleClass

{

public:

//static int getMyNumber() {return myNumber;} requires an object

static int getMyNumber() { return myValue;}

static int getMyStuff(SimpleClass *myClass) {return myClass-

>myNumber;}

static int getMyVal() {return myValue;}

static char myChar;

char myLetter;

private:

static int myValue;

int myNumber;

};

int SimpleClass::myValue=10;

char SimpleClass::myChar = 'a';

Page 25: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 25 -

C++ Class MembersC++ Class Members

Static Function Members

int main()

{

SimpleClass myClass, yourClass, *myClassPtr = &myClass ;

cout << SimpleClass::getMyStuff(myClassPtr) << endl;

cout << myClass.myChar << " " << SimpleClass::myChar << endl;

return 0;

}

int main()

{

SimpleClass myClass, yourClass, *myClassPtr = &myClass ;

cout << SimpleClass::getMyStuff(myClassPtr) << endl;

cout << myClass.myChar << " " << SimpleClass::myChar << endl;

return 0;

}

Page 26: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 26 -

C++ Class MembersC++ Class Members

Const Function MembersThe keyword const can be placed after argument list of member

function

syntax

returnType functionName ( argsi ) const { function body }

Tells compiler that function

Can only read data members

Cannot write them

Member functions declared const

Can be called for non-const objects

Non-const member functions

Cannot be called for const objects.

Page 27: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 27 -

C++ Class MembersC++ Class Members

Overloading Function Members

Functions can use same name in the same scope

If signature is unique

Name plus signature

Uniquely identify function

Same holds true for member functions

Same rules applied to disambiguate

Must provide Implementation for each overloaded function

Page 28: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 28 -

C++ Class MembersC++ Class Members

Operator Function MembersC++ defined operators can be overloaded to work on Class type

operands

Must take at least one class type argument

syntax

operator X (args) { body }

X is the operator symbol being overloaded

args - as appropriate for implementation

body - implements the function

Page 29: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 29 -

C++ Class MembersC++ Class Members

Operator Function Members

Invocation

Assume + is overloaded

Infix expression syntax

A + B

A, B can be member or non-member instances

Function call syntax

A.operator+ (B)

Page 30: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 30 -

C++ Class MembersC++ Class Members

Operator Function Members

Rules

Because operator functions are invoked using the same syntax

Operator functions...

1. Must have the same number of arguments as language defined versions

2. Must have the same precedence as the builtin operators…This cannot be overridden

3. Cannot have default parameters

4. Cannot override the predefined meaning

Page 31: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 31 -

C++ Class MembersC++ Class Members

Operator Function Members

Limitations

Because of the operator function syntax

1. Certain user defined operators cannot behave

analogously to built in versionsPrefix version

operator++ () {}

Postfix version

operator++ (int) {}

2. Some operators cannot be overloaded. , ?: :: . *

3. Some operators must be members only =, [ ] , ( ), ->

Page 32: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 32 -

C++ Class MembersC++ Class Members

Overloading Operators

class Complex{public:

int im, re;

Complex(int r=0, int i=0):re(r), im(i) { }

Complex operator+ (Complex a1) {return Complex(re+a1.re, im+a1.im);}

Complex& operator++ ()

{re += 1, im += 1; cout << “prefix" << endl; return Complex(re -1, im -1);

}Complex& operator++ (int) {

re+=1, im+=1;cout << "postfix" << endl; return *this;

}};

class Complex{public:

int im, re;

Complex(int r=0, int i=0):re(r), im(i) { }

Complex operator+ (Complex a1) {return Complex(re+a1.re, im+a1.im);}

Complex& operator++ ()

{re += 1, im += 1; cout << “prefix" << endl; return Complex(re -1, im -1);

}Complex& operator++ (int) {

re+=1, im+=1;cout << "postfix" << endl; return *this;

}};

Page 33: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 33 -

C++ Class MembersC++ Class Members

Operator Function MembersMember

Left hand operand must be an instance of class overloading

the operator

Unary

x.operator@()

x is class instance

Binary

x.operator(y)

x operator@ y

x is class instance

Page 34: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 34 -

C++ Class MembersC++ Class Members

Operator Function MembersNon-Member

If operator requires left hand operand of a different type…..

Must use non-member syntax Must be declared friend if the operator requires access to

protected or private members

Unary

operator@(x)

Binary

operator@(x,y)

x operator@ y

Page 35: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 35 -

C++ Class MembersC++ Class Members

Operators in ActionThe Copy Constructor and the Assignment Operator

There are many occasions when a copy of an object is needed

Object passed by value

x.func(y)

A copy of y is made and passed

Object returned by value

Object initialized by another object

ClassName x1 = x2

A copy of x2 is made

Object assigned to another objectx1 = x2x2 is copied to x1 and x1 is destroyed

Page 36: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 36 -

C++ Class MembersC++ Class Members

Operators in ActionThe Copy Constructor

A constructor that….. Takes a reference to an object of the same class as an

argument Performs initialization on newly created objects Used by compiler to copy objects by value

syntax

class X ( const class X& )

class X ( class X& )

Page 37: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 37 -

C++ Class MembersC++ Class Members

Operators in ActionThe Copy Constructor

If a copy constructor is not defined

Shallow bitwise copy performed - memcpy

If a copied object uses new to allocate memory when created

One must write a copy constructor

Copy constructor need only be written

If class object is passed by value

To prevent pass by value

Define a private copy constructor

Page 38: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 38 -

C++ Class MembersC++ Class Members

Operators in ActionThe Assignment Operator - operator=()

Called when one initialized object is to be assigned to a second.

The operator must serve as a destructor to the assignee object.

Can have a return value…

– The most common is *this

Is not called for the declarations such as

– ClassName object1 = object2

Page 39: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 39 -

C++ Class MembersC++ Class Members

Class Members - Friends

A class Definition….

Provides 3 levels of access to data and function members

public

protected

private

Closed Open

Page 40: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 40 -

C++ Class MembersC++ Class Members

Class Members - Friends

C++ provides means for more liberal access to non-public members

under specified set of conditions…..

Nonmember designated as a friend of the class

Class friend is designated by

Keyword friend

Followed by class name

Page 41: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 41 -

C++ Class MembersC++ Class Members

Class Members - Friends

Once an object is designated as a friend….

It has access to non-public members as if they were public

If B is designated as friend of A

B can access A’s non-public members

A cannot access B’s

Page 42: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 42 -

C++ Class MembersC++ Class Members

Class Members - Friends

Friend may be:

1. Class

friend class X;

2. A particular function

friend int sub (int y);

3. A particular class member

friend int Mult::get();

Page 43: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 43 -

C++ Class MembersC++ Class Members

Class Members - Friends

A friend does not have a this pointer unless it is a member function in

its own right

Question:

If it is a member function which this pointer does it have

Class A a;

Class B b;

Let B be declared as a friend of A

The this pointer of a function bFunct() contains

the address of the class instance b

Page 44: C++ Class Members

Copyright 2006 Oxford Consulting, Ltd

1 February 2006

- 44 -

C++ Class MembersC++ Class Members

Class Members - Friends

Caveats and Problems,,,

Friends can have access to everything … this defeats datahiding.

Introduces extra coupling between classes.

Permits change of internal state from the outside.

Should use member functions not friends to change state.