Archive

Posts Tagged ‘member function’

C++ Tip – this

You probably all know about the this pointer already, but I just answered a question about it on cplusplus.com, so I thought that I may as well post here while it’s at the forefront of my mind!

So this is a keyword which we can use inside a member function. It is a pointer to the instance of the class from which the member function was called. Still not sure? Check out the following example program.

#include <iostream>
class foo {
public:
   void bar() { std::cout << this << std::endl; }
};

int main()
{
   using namespace std;
   foo foo1, foo2;
   cout << "foo1\n" << &foo1 << endl;
   foo1.bar();
   cout << "foo2\n" << &foo2 << endl;
   foo2.bar();

   return 0;
}

This program yielded the following output for me.

foo1
0031F916
0031F916
foo2
0031F917
0031F917

For you, the actual numerical values of the addresses may be different, but the point is that the address of foo1 is the same as the value printed by foo1.bar() (which prints the this pointer) and the address of foo2 is the same as the value printed by foo2.bar().

So, if you couldn’t before, you can now hopefully understand what I mean when I say that the this pointer points to the instance of the class from which the member function was called.

Interesting Point: Notice that the address of foo1 is only 1 behind the address of foo2. We created the two variables on the same line as stack variables, so they are in adjacent memory locations. However, as the classes are effectively empty, the memory locations are in fact even consecutive (each instance takes only one space on the stack).

Notes
  1. Remember that this may only be used from inside member functions (think about it – it wouldn’t make much sense anywhere else)
  2. this cannot be used in a constructor’s initializer list, but it can be used in its body
  3. this can be used in a destructor’s body, but be careful as if the class is being destroyed you probably don’t want to go around handing its address out to other functions and variables
Follow

Get every new post delivered to your Inbox.

Join 77 other followers