Why do we use the reference operator twice? - c++

My question refers to pointers with classes and the keyword this.
class class1 {
public:
bool isitme(class1& temp){
if(this == &temp)
return true;
else return false;
}
};
int main () {
class1 c3;
class1* c2 = &c3;
if(c3.isitme(*c2))
cout << "c3 == c2"; //it is returning that
system("pause");
}
The code above is working, but what I do not understand is why it works only when bool isitme(class1& temp) and if(this == &temp) are in the same function isitme().
I mean, we already read the block of memory class1& temp of temp in the class parameters and should be able to compare that block of memory with the keyword this. Why is the function only true when I double get the reference (this == &temp)?
Thanks

this is a pointer, whereas temp is a reference. When you write &temp in your if statement, you are taking the address of temp. This converts it to a pointer that can then be compared to this.

Do not confuse reference declarations with use of the address-of operator. When & identifier is preceded by a type, such as int or char, then identifier is declared as a reference to the type. When & identifier is not preceded by a type, the usage is that of the address-of operator.
Taken from: http://msdn.microsoft.com/en-us/library/w7049scy(v=vs.71).aspx

It's been a while since c/c++ days, but let me take a stab at this...
You're not using the reference operator twice. When you specify class1& you're only specifying the type of the parameter (the type is "reference of type class1"), not actually doing anything to temp. Later you actually dereference the parameter with &temp. It's only the second appearance of the ampersand that actually is a reference operator.

The & operator within the method declaration simply means that the object passed should not be copied, but rather point to the same location as the object passed to it (it's a reference). The & operator in if(this == &temp) is needed to actually get the address of that object (a pointer) so that you can compare it to the this pointer.

The reference "operator" in the signature of the isitme method denotes a reference, that is, an alias for the object itself.
On the other hand, in the line if(this == &temp), the operator is used directly on the object and thus returns the address of the object (a pointer to it).
So, if you want to check if the entered reference is equal to this, you need to compare to a pointer, which is exactly what the referance operator returns.

& in the class parameter list means the object is passed by-reference. That is, temp is an alias for the class1 object. &temp is simply taking the address of that object and comparing it to the object pointed to by this. The two syntaxes are semantically different, you're not taking the address twice.

Related

Why do we return *this in asignment operator and generally (and not &this) when we want to return a reference to the object?

I'm learning C++ and pointers and I thought I understood pointers until I saw this.
On one side the asterix(*) operator is dereferecing, which means it returns the value in the address the value is pointing to, and that the ampersand (&) operator is the opposite, and returns the address of where the value is stored in memory.
Reading now about assignment overloading, it says "we return *this because we want to return a reference to the object". Though from what I read *this actually returns the value of this, and actually &this logically should be returned if we want to return a reference to the object.
How does this add up? I guess I'm missing something here because I didn't find this question asked elsewhere, but the explanation seems like the complete opposite of what should be, regarding the logic of * to dereference, & get a reference.
For example here:
struct A {
A& operator=(const A&) {
cout << "A::operator=(const A&)" << endl;
return *this;
}
};
this is a pointer that keeps the address of the current object. So dereferencing the pointer like *this you will get the lvalue of the current object itself. And the return type of the copy assignment operator of the presented class is A&. So returning the expression *this you are returning a reference to the current object.
According to the C++ 17 Standard (8.1.2 This)
1 The keyword this names a pointer to the object for which a
non-static member function (12.2.2.1) is invoked or a non-static data
member’s initializer (12.2) is evaluated.
Consider the following code snippet as an simplified example.
int x = 10;
int *this_x = &x;
Now to return a reference to the object you need to use the expression *this_x as for example
std::cout << *this_x << '\n';
& has multiple meanings depending on the context. In C and used alone, I can either be a bitwise AND operator or the address of something referenced by a symbol.
In C++, after a type name, it also means that what follows is a reference to an object of this type.
This means that is you enter :
int a = 0;
int & b = a;
… b will become de facto an alias of a.
In your example, operator= is made to return an object of type A (not a pointer onto it). This will be seen this way by uppers functions, but what will actually be returned is an existing object, more specifically the instance of the class of which this member function has been called.
Yes, *this is (the value of?) the current object. But the pointer to the current object is this, not &this.
&this, if it was legal, would be a pointer-to-pointer to the current object. But it's illegal, since this (the pointer itself) is a temporary object, and you can't take addresses of those with &.
It would make more sense to ask why we don't do return this;.
The answer is: forming a pointer requires &, but forming a reference doesn't. Compare:
int x = 42;
int *ptr = &x;
int &ref = x;
So, similarly:
int *f1() return {return &x;}
int &f1() return {return x;}
A simple mnemonic you can use is that the * and & operators match the type syntax of the thing you're converting from, not the thing you're converting to:
* converts a foo* to a foo&
& converts a foo& to a foo*
In expressions, there's no meaningful difference between foo and foo&, so I could have said that * converts foo* to foo, but the version above is easier to remember.
C++ inherited its type syntax from C, and C type syntax named types after the expression syntax for using them, not the syntax for creating them. Arrays are written foo x[...] because you use them by accessing an element, and pointers are written foo *x because you use them by dereferencing them. Pointers to arrays are written foo (*x)[...] because you use them by dereferencing them and then accessing an element, while arrays of pointers are written foo *x[...] because you use them by accessing an element and then dereferencing it. People don't like the syntax, but it's consistent.
References were added later, and break the consistency, because there isn't any syntax for using a reference that differs from using the referenced object "directly". As a result, you shouldn't try to make sense of the type syntax for references. It just is.
The reason this is a pointer is also purely historical: this was added to C++ before references were. But since it is a pointer, and you need a reference, you have to use * to get rid of the *.

how *return implicitly return a reference

this is a const ptr to the object/instance which a member function receive implicitly, so how does return *this returns a reference ?
As of what I know , a pointer dereferencing to a variable means it holds it's memory address , so return *this should return value dereferenced by this const pointer which is what? An object?
Also, why you can't do something like this:
Calc cCalc;
cCalc.Add(5).Sub(3).Mult(4);
Without having all that member functions to return *this?
I would want to know how pointers and reference treat objects/instances.
Let's try to untangle:
this is a const ptr to the object/instance which a member function receive implicitly
member functions indeed receive this pointer implicitly. The type is T* or const T* depending on the member function signature -- you get const placing const keyword at the tail after the ().
so how does return *this returns a reference ?
*this dereference the pointer, thus creating lvalue of type T or const T respectively. If your question is meant how you get T& from *this in a const funstion, the answer that you don't, that attempt would be ill-formed code.
As of what I know , a pointer dereferencing to a variable means it holds it's memory address , so return *this should return value dereferenced by this const pointer which is what? An object?
*this denotes the instance. And it is lvalue expression. So you can get its address agan (providing same as this), or can bind it to a reference -- including the case for a return.
The chaining you show can actually be done if the functions returned Calc instead of Calc& or returned some different object than *this -- but then the result of calculations would end up in that place. Not where you expect it: in cCalc.
As it stands, when all three functions return *this leads first Add taking &cCalc in this, and returns cCalc. The next call to Sub has the same situation. And Multiply too.
Add member doesnt have Sub function. Compiler give an error.
But, if you return *this, you are returning your own object (not reference). Now you have one cCalc object that can use Sub(3). Sub(3) return your object and can use Mult(4).

C++ interview about operator

Here is the code which basically implementing the = assignment for a class named CMyString, and the code is right.
CMyString& CMyString::operator =(const CMyString &str) {
if(this == &str)
return *this;
delete []m_pData;
m_pData = NULL;
m_pData = new char[strlen(str.m_pData) + 1];
strcpy(m_pData, str.m_pData);
return *this;
}
The instance is passed by reference, and the first 'if' is checking whether the instance passed in is itself or not. My question is: why does it use &str to compare, doesn't str already contain the address of the instance? Could any one explain how this line works?
Also, I just want to make sure that this contains the address of the object: Is this correct?
isn't str already contains the address of the instance
No. A reference is the object itself. It's not a pointer to the object.
(I. e., in the declaration of the function, &str stands for "reference to str" and not "address of str" - what you're talking about would be right if the function was declared like this:
CMyString& CMyString::operator =(const CMyString *str);
but it isn't.)
Address-of Operator and Reference Operator are different.
The & is used in C++ as a reference declarator in addition to being the address-of operator. The meanings are not identical.
int target;
int &rTarg = target; // rTarg is a reference to an integer.
// The reference is initialized to refer to target.
void f(int*& p); // p is a reference to a pointer
If you take the address of a reference, it returns the address of its target. Using the previous declarations, &rTarg is the same memory address as &target.
str passed by to the assignment operator is passed by reference, so it contains the actual object, not its address. A this is a pointer to the class a method is being called on, so if one wants to compare, whether passed object is the same object itself, he has to get the address of str in order to compare.
Note, that & behaves differently, depending on where it is used. If in statement, it means getting an address to the object it is applied to. On the other hand, if it is used in a declaration, it means, that the declared object is a reference.
Consider the following example:
int i = 42;
int & refToI = i; // A reference to i
refToI = 99;
std::cout << i; // Will print 99
int j = 42;
int * pJ = &j; // A pointer to j
*pJ = 99;
std::cout << j; // Will print 99
this is a pointer to the instance, so yes, it contains the address.
The whole point of verifying, if the passed object is this or not is to avoid unnecessary (or, possibly destructive) assignment to self.
While indeed a variable reference - denoted by the symbol & after the type name - underlying implementation is usually a pointer, the C++ standard seemingly does not specify it.
In its usage anyway, at the syntax level, a reference is used like a non referenced value of the same type, ie. more strictly speaking :
If the type of the variable is T &, then it shall be used as if it were of type T.
If you must write str.someMethod() and not str->someMethod() (without any overloading of the arrow operator), then you must use & to obtain the address of the value. In other words, a reference acts more or less like an alias of a variable, not like a pointer.
For more information about references and pointers, see these questions:
What's the meaning of * and & when applied to variable names?
What are the differences between a pointer variable and a reference variable in C++?
Why 'this' is a pointer and not a reference?

Constant Reference Wrapper

I came across the following piece of code in the book on data structures by Mark Allen Weiss.
template <class Object>
class Cref
{
public:
Cref ( ) : obj ( NULL ) { }
explicit Cref( const Object & x ) : obj ( &x ) {
const Object & get( ) const
{
if ( isNull( ) )
throw NullPointerException( ) ;
else
return *obj;
}
bool isNull( ) const
( return obj == NULL; }
private:
const Object *obj;
};
So the point here is to assign null/initialize a constant reference. But I am not sure I understand the following:
1. We initialize a constant reference with another constant reference x. But why is it again done as obj(&x) ? the & in const Object & x is different from the &x in obj(&x) ? I see this but not very clear why it should be so. Pls explain.
2. The get method() - We try to return a const reference of the private member obj of this class. It is already a const reference. Why return *obj and not just obj ?
3. Why explicit keyword ? What might happen if an implicit type conversion takes place ? Can someone provide a scenario for this ?
Thanks
The member obj is of type Object*, but the constructor takes a reference. Therefore to get a pointer, the address-of operator, &, has to be applied. And the member is a pointer because it can be NULL (set in the default constructor), and references never can be NULL.
The private member is not a const reference, but a poinetr to const. It is dereferenced to get a reference.
In this specific case, I cannot see any negative effect of a potential implicit conversion either.
1) &x in obj(&x) is used as the address-of operator.
2) No, it is a pointer. Its time is Object *, not Object &.
3) To prevent casting from incompatible pointer types which might have their own type-cast operator.
C++ has three flavors of null available:
NULL - obsolete; use it only for checking the return values of C functions which return pointers
0 - deprecated; the literal zero is defined in the Standard to be the null pointer
nullptr - as of C++11, this is the preferred way of testing for null. Furthermore, nullptr_t is a type-safe null.
1) The token & has three meanings:
Unary address-of operator: Take the address of any lvalue expression, giving a pointer to that object.
Reference sigil: In a declaration, means a reference type.
Binary bitwise AND operator - not used here
So it's important to know whether you're looking at a declaration or an expression.
explicit Cref( const Object & x )
Here the sigil appears in the declaration of a function parameter, meaning the type of parameter x is a reference to an Object which is const.
: obj ( &x ) {}
Here the operator is used in a member initializer expression. Member obj is initialized to be a pointer to x.
2) Since member obj is actually a pointer, the dereference operator unary * is needed to get a reference.
3) In general, it's a good idea to use explicit on any (non-copy) constructor which can take exactly one argument. It's just unfortunate that the language doesn't default to explicit and make you use some sort of "implicit" keyword instead when you mean to. In this case, here's one rather bad thing that could happen if the constructor were implicit:
Object create_obj();
void setup_ref(Cref& ref) {
ref = create_obj();
}
No compiler error or warning, but that setup_ref function stores a pointer to a temporary object, which is invalid by the time the function returns!
1) The type of obj is not a reference, obj is a pointer, and a const pointer must be initialized with a address, so, the address-of operator, &, must be applied.
2) The reference the get() method returns is not a reference to the class member obj, but a reference to the object which obj points, so you have to use * to deference it.
3) The keyword explicit means we reject the implicit conversions, that is, we tell the compiler, don't make implicit conversions with this constructor for us.
Example:
class Cref<Object> A;
Object B;
A=B;
It's OK without the explicit--Since we need a Cref object on the right side, the compiler will automate making a Cref object with constructor Cref( const Object & B ). But if you add an explicit, the compiler won't make conversions, there will be a compiling error.

by reference in C++

I have this snippet of the code
Stack& Stack:: operator=(const Stack& stack){
if(this == &stack){
return *this
}
}
here I define operator = but I can't understand, if I receive by reference stack why it should be & in this == &stack and not this == stack and why we return * in return *this and not this thanks in advance for any help
Because this is a pointer (i.e. of type Stack*), not a reference (i.e. not of type Stack&).
We use if(this == &stack) just to ensure the statement
s = s;
can be handled correctly (especially when you need to delete something in the old object). The pointer comparison is true only when both are the same object. Of course, we could compare by value too
if (*this == stack)
return *this;
else {
...
}
But the == operation can be very slow. For example, if your stack has N items, *this == stack will take N steps. As the assignment itself only takes N steps, this will double the effort for nothing.
stack is of type Stack&, and this is of type Stack*. You're checking if the address of stack is equal to this.
Short answer to your two questions.
As I understand you ask why we use & sign if we get reference as a function parameter(not an abject). Because reference to an abject is not address of it. You should use operator&() in order to get the address of an object.
this is a pointer, but you should return reference thus you return *this
if I receive by reference stack why it should be & in this == &stack
Because this is a pointer (or "address") and stack is a reference (not a pointer): so you need to say &stack (which means "address of stack"), so that its type matches the type of this.
why we return * in return *this and not this
Because this is a pointer (not a reference), but the method is supposed to return a reference (not a pointer), so you need to deference it in order to turn the pointer into a reference.