this
All C++ classes have a pointer called this
that refers to the
current object. This is useful, since some functions, as we will see,
need to return a reference to the object we are working on.
Here’s a very simple example that creates a class that only holds a
string and then defines a member function, get_ref()
, that returns
a reference to itself (by returning *this
as a reference).
#include <iostream>
class Example {
private:
std::string data;
// simple constructor
public:
Example(const std::string& input_string) : data{input_string} {};
// getter
std::string get_data() {return data;}
// function that returns a reference -- just for demostration
Example& get_ref() {return *this;}
};
int main() {
Example test("this is my test string");
Example& new_class = test.get_ref();
std::cout << new_class.get_data() << std::endl;
}
Another way we could use this
is to access the member data inside of
the class. Since this
is a pointer, we will use the member selection
operator for pointers, e.g., this->data
.