EC-241 Object Oriented Programming

wakecabbagepatchΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

80 εμφανίσεις

LECTURE 6

The
this

Pointer


Every

object

has

access

to

its

own

address

through

a

pointer

called

the

this

pointer
.


The

this

pointer

is

passed

by

the

compiler

as

an

implicit

argument

to

each

of

the

object’s

non
-
static

member

functions


class test

{


public:



test(int=0);



void print()const;


private:



int x;

}



test::test(
int

val
) : x(
val
) {

}


void test::print() const

{


//implicitly use the this pointer to access //member x



cout
<<x;



//explicitly use the this pointer and the arrow
//operator to access member x



cout
<<this
-
>x;


//explicitly use the
dereferenced

this pointer //and the
dot operator to access member x



cout
<<(*this).x;

}


int main()

{


test t1(12);


t1.print();


return 0;

}


Output: ?



Dynamic Memory Management

Example 1:


Time *
timePtr
;


timePtr
=new Time;


delete
timePtr
;


Example 2:



Time *
timePtr
=new Time(12, 45,0);


Example 3:


int

*arrayexample = new int[10];




delete []
arrayexample
;





class Employee

{

private:


char *
firstName
;


char *
lastName
;


public:

Employee( char * first, char * const last )

{


firstName

= new char[
strlen
( first ) + 1 ]; // create space


strcpy
(
firstName
, first ); // copy first into object



lastName

= new char[
strlen
( last ) + 1 ]; // create space


strcpy
(
lastName
, last ); // copy first into object



cout

<< "Employee constructor for " <<
firstName
<< ' ' <<
lastName

<< " called." <<
endl
;

}

~Employee()

{


cout

<< "~Employee() called for " <<
firstName
<< ' ' <<
lastName

<<
endl
;



delete []
firstName
; // release memory


delete []
lastName
; // release memory



count
--
; // decrement static count of employees

}

}; // end class Employee