You are here:

C++/this pointer

Advertisement


Question
In operator overloading , we often  return this pointer from a operator function. But the return type of the operator function is the class name. Not pointer to that class.How does it return a pointer ?

Answer
Hello Shahed, thank you for the question.

The return type of the operator overload specifies the type of variable that it returns. So if you want to return a class reference, you simply provide the name of the class:

Foo& operator += (const Foo &rhs)
{
this->value += rhs.value;
return *this;
}

The this pointer is a pointer to the invoking object. That is, whatever object calls that method in code. You are simply return the object who called it's own method. In this case, it's of type Foo.

// In main
Foo f, g;

f += g;

So when += is called, f would be the invoking object. You could compare f to this in the function, and they would be equal.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.