Object Oriented Programming - Old Questions

8. What is this pointer? How can we use it for name conflict resolution?Illustrate with example.

5 marks | Asked in 2076

We can use keyword "this" to refer to this instance inside a class definition. One of the main usage of keyword this is to resolve ambiguity between the names of data member and function parameter. For example,

class Circle {

private:

   double radius;                 // Member variable called "radius"

   ......

public:

   void setRadius(double radius)   // Function's argument also called "radius"

   { 

      this->radius = radius;

         // "this.radius" refers to this instance's member variable

         // "radius" resolved to the function's argument.

   }

   ......

}

In the above codes, there are two identifiers called radius - a data member and the function parameter. This causes naming conflict. To resolve the naming conflict, we could name the function parameter r instead of radius. However, radius is more approximate and meaningful in this context. We can use keyword this to resolve this naming conflict. "this->radius" refers to the data member; while "radius" resolves to the function parameter. "this" is actually a pointer to this object.