Using the C++ 'this' pointer explicitly to point to the class object member code sample

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ 'this' pointer explicitly to refer to the class object members

To show: How to use the hidden C++ 'this' pointer explicitly in C++ programming

 

// using the this pointer explicitly to refer to the object members

#include <iostream>

using namespace std;

 

class ThiPoint

{

int c;

public:

ThiPoint(int);

void display();

~ThiPoint();

};

 

// constructor method/function

ThiPoint::ThiPoint(int a)

{

cout<<"A constructor..."<<endl<<endl;

c = a;

}

 

// printing method/function

void ThiPoint::display()

{

cout<<"Direct access: c = "<<c<<endl;

cout<<"Arrow operator: this->c = "<<this->c<<endl;

// use parentheses for (*this).c because dot has higher precedence than *

cout<<"Pointer and dot operator: (*this).c = "<<(*this).c<<endl;

}

 

ThiPoint::~ThiPoint()

{

cout<<endl<<"A destructor..."<<endl;

}

 

void main(void)

{

int x = 100;

 

cout<<"Using the C++ this pointer explicitly"<<endl;

ThiPoint b(x);

b.display();

 

return;

}

 

Output example:

 

Using the C++ this pointer explicitly

A constructor...

Direct access: c = 100

Arrow operator: this->c = 100

Pointer and dot operator: (*this).c = 100

A destructor...

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index