C++ "this" Pointer

Member functions of C++ objects can access a 'magic' pointer to themselves. That pointer, which points to the object itself, is the this pointer. So any member function can lookup the address of the object that invoked the function. Here is a very simple program to illustrate that concept.

// Filename: locator.cpp
// Purpose:  Illustrate the use of the "this" pointer.
//
#include <iostream.h>

class locator
    {
    public:

	void whereami() // define a member function
	     {
	     cout << "My current address is: " << this  << endl;
	     }
    private:

    };

int main()
{
    cout << "\nThis program demonstrates use of the 'this' pointer.\n\n";

    locator tom; // instantiate an object of the class "locator"
    locator dick;
    locator harry;

    tom.whereami(); // call the member function to get the value of "this"
    dick.whereami();
    harry.whereami();

    cout << "\nEnd of demonstration.\n";
    return(0);

} // end main
And here is what that program outputs:
	This program demonstrates use of the 'this' pointer.

	My current address is: ffbef98b
	My current address is: ffbef98a
	My current address is: ffbef989

	End of demonstration.
Note that some implementations automatically print pointers in hex, but it is not universal.


Last modified: Sunday, 25-Mar-2012 17:20:52 CST
Copyright 2002 Department of Computer Science, University of Regina.


 CS Dept Home Page

Teaching Material