Tuesday, October 19, 2010

Creating user defined this pointer in C++

  1. For creating user defined this pointer, we have to know the behavior of this pointer.
  2. Behavior of this pointer
  • It is a constant pointer.
  • It always points to the current class object.
  • When a member function is called with respect to an object, an extra hidden parameter is passed to every member fuction, that hidden parameter is a pointer which stores the address of current object, known as this pointer.
  • Example:     int add(int a, int b)
    internally
      C++ attaches a pinter to this member function
               int add(Sample*const this,int a,int b)
            Where Sample is the class name, this first parameter attached by compiler internally. 
3. Like this manually we can attach an Extra parameter to our method
       int add(Sample * const p,int a, int b){
              return a+b;
        }
4. While calling this member function call like this
       Sample s;
       s.add(&s,10,20)

This is not practically very useful but it helps to know the internal behavior of this pointer and how this pointer is implemented in C++.