You get a bonus - 1 coin for daily activity. Now you have 1 coin

1.6. This pointer

Lecture



When a class member function is called to process data of a specific object, a pointer to the object for which the function is called is automatically and implicitly passed to this function. This pointer is named this and is implicitly defined in each function of the class as follows.

class_name * const this = object_address

The this pointer is an additional hidden parameter of each non-static component function. When entering the body of the function belonging to the class, this is initialized with the address value of the object for which the function was called. As a result, the object becomes available inside this function. In most cases, the use of this is implicit. In particular, every call to a non-static member function of a class implicitly uses this to access the member of the corresponding object. For example, the add function in the class complex can be defined in an equivalent, albeit more extensive way:

void complex add (complex ob)
{this-> re = this-> re + ob.re;
// or
* this.re = * this.re + ob.re
this-> im = this-> im + ob.im;}

If the function returns the object that called it, the this pointer is used.
For example, let the add function return an object reference. Then

complex &
complex add (complex & ob)
{re = re + ob.re; im = im + ob.im; return * this; }

An example of the common use of this is related list operations.

Example 1.6.1

// Related list

#include <iostream.h>

// class definition

class item

{

static item * begin;

item * next;

char symbol;

public:

item (char ch) {symbol = ch;} // constructor

void add (void); // add to the beginning

static void print (void);

};

// class implementation

void item:: add (void)

{

this -> next = begin;

begin = this;

}

void item:: print (void)

{

item * p;

p = begin;

while (p! = NULL)

{

cout << p -> symbol << “\ t”;

p = p -> next;

}

}

// Create and view the list

item * item:: begin = NULL; // initialize the static component

void main ()

{

item A ('a'); item B ('b'); item C ('c');

// include objects in the list

A.add (); B.add (); C.add ();

// view the list in reverse order

item :: print ();

}


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

C ++ (C plus plus)

Terms: C ++ (C plus plus)