Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

The this Pointer in C++

C++ this Pointer

C++ Classes & Objects C++ Classes & Objects

In C++,this The this pointer is a special pointer that points to the instance of the current object.

In C++, every object can access its own address through this the this pointer.

thisthe this pointer is a hidden pointer that can be used in a class's member functions to point to the calling object.

When a member function of an object is called, the compiler implicitly passes the object's address as the this pointer.

Friend functions do not have this the this pointer, because a friend is not a member of the class; only member functions have this pointer.

The following example helps to better understand the concept of the this pointer:

Example

#include

<
iostream
class
MyClass
{
private

:

int

value

;

public

:

void

setValue

(

int

value

)

{

this

->

value

=

value

;

}

void

printValue

(

)

{

std

::

cout

<<

"

Value:

"

<<

this

->

value

<<

std

::

endl

;

}

}

;

int

main

(

)

{

MyClass

obj

;

obj

.

setValue

(

42

)

;

obj

.

printValue

(

)

;

return

0

;

}

The output of the above code is:

Value: 42

Example analysis:

More examples

The following example compares the volumes of cuboids:

Example

#include

<
iostream
using
namespace
std

;

class

Box

{

public

:

// Constructor definition

Box

(

double

l

=

2

.0

,

double

b

=

2

.0

,

double

h

=

2

.0

)

{

cout

<<

"

Constructor called.

"

<<

endl

;

length

=

l

;

breadth

=

b

;

height

=

h

;

}

double

Volume

(

)

{

return

length

breadth

height

;

}

int

compare

(

Box

box

)

{

return

this

->

Volume

(

)

box

.

Volume

(

)

;

}

private

:

double

length

;

// width

double

breadth

;

// length

double

height

;

// height

}

;

int

main

(

void

)

{

Box

Box1

(

3

.3

,

1

.2

,

1

.5

)

;

// Declare box1

Box

Box2

(

8

.5

,

6

.0

,

2

.0

)

;

// Declare box2

if

(

Box1

.

compare

(

Box2

)

)

{

cout

<<

"

The volume of Box2 is smaller than that of Box1

"

<<

endl

;

}

else

{

cout

<<

"

The volume of Box2 is greater than or equal to that of Box1

"

<<

endl

;

}

return

0

;

}

When the code above is compiled and executed, it produces the following result:


调用构造函数。
调用构造函数。
Box2 的体积大于或等于 Box1

C++ Classes & Objects C++ Classes & Objects