-12

Would passing an object to a member function or a constructor be a good use of explicitly using a this pointer? such as a pass by reference?

 class Something
{
private:
    int m_data;

public:
    Something(int data ->&obj)
    {
        this->data = m_data;
    }
};
Rolando
  • 11
  • 4

1 Answers1

1

When is using the “this pointer” useful in a C++ program

When you need a pointer to the current object.

One of the most often usages of this that I have seen is to make self assignment a noop.

Foo& Foo::operator=(Foo const& rhs)
{
   if ( this != &rhs )
   {
      // Assign only when the objects are different
   }
   return *this;
}

I haven't seen this as much but you can do the same simplification for operator==.

bool Foo::operator==(Foo const& rhs) const
{
   if ( this == &rhs )
   {
      return true;
   }

   // Do the real work for objects that are different.
   // ...
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270