-
September 18th, 2009, 08:16 PM
#1
(this == &s) vs (this == s)
Hi,
I was trying to write overloaded == operator for string class. When I use only "s" instead of "&s" in the statement "this == &s", I get the following error. My question is: Is not "s" a reference already, so why do I need to specify "&s". What exactly does a prefix of "&" to a reference mean? (Book by Lippman but that does not seem to address this)
str.cpp: In member function `String& String:perator=(const String&)':
str.cpp:55: error: no match for 'operator==' in 'this == s'
class String {
....
String& operator = (const String &s) {
if (!(this == &s)) {
char *temps = str;
str = new char[sizeof(s.c_str())];
strcpy(str, s.c_str());
delete temps;
}
return *this;
}
private:
char *str;
};
-
September 18th, 2009, 08:37 PM
#2
Re: (this == &s) vs (this == s)
The & operator actually has two different meanings dependent on context. In a variable declaration, including the special case of parameter passing, it declares a reference. That's something C++ has, it wasn't in C.
However, the old C meaning of & still applies: Anywhere else it is used, it means "address of". So essentially, it converts any object into a pointer to that object.
Since "this" is a pointer to the current object, then if s is a reference to an object of the same type, you can do one of two things:
Code:
if (this == &s) // checks if the address of s is the same as this, eg, checks that the two are *actually*
// the exact same object.
if (*this == s) // uses the class's overloaded == operator, if any, to check whether s is logically
//equivalent to the current object. It does not have to be the same actual object, although naturally
//any object should be logically equivalent to itself.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|