when is object a pointer? |
Err.. this question doesn't really make sense in this context. Objects and pointers are two entirely different things.
Objects are "things". For example if I say:
string foo;
, that means that foo actually is a string. On the other hand, pointer are not objects themselves, but rather they tell you where to find / how to access other objects.
string* bar;
bar is not a string, it tells you where to find a string. However,
*bar
is a string, assuming bar points to a valid object.
The
this
keyword gives you a pointer to the "current" object being acted on. Simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class ShowThis
{
public:
void print()
{
cout << this; // 'this' is the address of whatever object we're acting on
cout << endl;
}
};
int main()
{
ShowThis a, b; // create two objects
a.print(); // since we're acting on 'a', 'this' will point to 'a'
b.print(); // but now, 'this' will point to 'b' because we're acting on b
// A simple way to test:
cout << &a << " = "
a.print(); // will print the same address twice
cout << &b << " = "
b.print(); // ditto
}
|
The code snippit you posted is a common technique:
1 2 3 4 5 6
|
String& operator=(const String& rhs)
{
if(this == &rhs)
return *this;
//...
}
|
This is known as "preventing self assignment". If
this == &rhs
is true, that means that an object is being assigned to itself. For instance if you did this:
1 2
|
string a = "foo";
a = a; // self assignment
|
In this case, the assignment operator doesn't need to do anything (and probably shouldn't), so it can just exit early.
And also: when returning object(in class method of course), you can only return it with pointer or reference to it rigth? Theres no other way. |
You can also return a copy of it by value, but if you want to return the original object (and not a copy), then yes it has to be by ref or by pointer.