Let‘s assume you‘ve gote a class, for example
1 2 3 4 5 6
|
class MyClass {
private:
// something here
public:
// some stuff here
};
|
You can easily define an instance of that class:
1 2 3 4 5
|
int main()
{
MyClass m;
return 0;
}
|
And you can easily get the memory address of that object (i.e. of that instance of MyClass):
1 2 3 4 5 6 7
|
int main()
{
MyClass m;
MyClass* p_to_m = &m; // &m == memory address of m
return 0;
}
|
So, getting the address of an instance of a class from
outside the class looks pretty simple.
But how do you get the address of an instance of a class from
inside the class definition?
In other words, if you want your class to say: here you are my address (the address of this instance), how can you achieve that?
That‘s what is
this
--> the address of the current instance of the class.
If you are asking what it could come at handy for, maybe super simple examples are hard to find, but its usage is pretty common.
For example, the overloaded prefix operator++ is usually somewhat like:
1 2 3 4 5 6 7 8 9 10 11
|
class MyClass {
int myproperty {};
public:
// some stuff here
MyClass& MyClass::operator++()
{
myproperty++;
return *this; // the content of the memory address of this instance
// of this class
}
};
|
In your code:
1 2 3 4 5
|
class Complex
{
double real;
double imag;
...
|
1 2 3 4
|
int main()
{
Complex z(2.0, 3.0); // now real == 2.0 and imag == 3.0
z.conjugate()
|
The coniugate() method returns an instance of class Complex:
1 2 3 4 5 6 7 8 9 10
|
// return the modified Complex object
Complex conjugate()
{
imag *= -1.0;
return *this; // an instance of Complex is returned.
// Which one? The one at the memory address of z.
// Yes, it means a copy of z. If the function declaration were
// Complex & conjugate()
// it would have been z itself.
}
|
1 2 3 4 5
|
int main()
{
Complex z(2.0, 3.0);
z.conjugate().print(); // since coniugate() returns an instance of Complex,
// you can invoke print() directly from there.
|