I am working with Teach Yourself C++ in 21 Days and am attempting to self-teach. I am trying to grasp the this pointer and when to use it. Anyone who is willing to explain this to me please do. Thank you in advance.
I am working with Teach Yourself C++ in 21 Days and am attempting to self-teach. I am trying to grasp the this pointer and when to use it. Anyone who is willing to explain this to me please do. Thank you in advance.
Not totally sure on the exact syntax, but basically you are implicitly returning a pointer to the structure at hand. It's limited to non-static member functions.
class foo:ublic bar{ long ID;};
foo::BoundsCheck{
if( this->ID <=1010101)
return *this;
return NULL;
}
Not so sure that'd compile but you get the idea.
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
Use it when you want to return the current object, or see if a passed object is the same object as the reciever of the message. For example, if you were to write your own comparsion operation for a class, it might look like this.
The this pointer isn't used explicitly all that much, however.Code:class Foo { public: bool equals(const Foo& other); // other stuff private: char bigString[1024]; }; bool Foo::equals(const Foo& other) { if (this == &other) { // compare pointers, if they are at same location, they are obviously same object, and can avoid costly bigString compare return true; } return strcmp(bigString, other.bigString) == 0; }