Question About & operator in C++ - c++

I am looking at the .h file of a Wrapper class. And the class contains one private member:
T* dataPtr;
(where T is as in template < class T > defined at the top of the .h file)
The class provides two "* overloading operator" methods:
T& operator*()
{
return *dataPtr;
}
const T& operator*() const
{
return *dataPtr;
}
Both simply return *dataPtr, but what does the notation "*dataPtr" actually return, in plain English? And how does it fit with the return type "T&"?

The return type T& states that you are returning a reference of an instance of a T object. dataPtr is a pointer, which you "dereference" (get the reference value/instance of a pointer) using *.

dataPtr is a pointer to something.
The * operator dereferences the pointer, so *dataPtr is (or, instead of 'is', you can say 'refers to' or 'is a reference to') the pointee, i.e. the thing that dataPtr is pointing to.
T& means 'a reference to an object whose type is T' (not to be confused with T* which means 'a pointer to an object whose type is T').

*DataPtr is the actual data pointed to by DataPtr. Both operators return a reference to T. A reference is a type that you should think of like another name for the value it refers to. "Under the hood," it is similar to a pointer, but don't think of it that way. It can't do pointer math, or be "reseated." One of the operators is const and is used on a const object, and the other is used on a normal object.

The wrapper class seems to be acting like a C++ pointer.
Operator * dereferences the wrapper which will evaluate to the thing it stores (in dataPtr). What you get is a reference to this contents. E.g. you can assign something to the reference
*intWrapper = 42;
There are two operators because there is a constant and a non-constant version. When you dereference a constant wrapper class, you can't assign to it (a const reference (T&) is returned)

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 *.

Don’t understand this return type?

I’m reading some code my teacher gave me and I don’t quite understand one specific line of code. The function returns an int&.
return (*(Vector *)this)[i];
this return statement is in an operator overload of “[]”. There is also another operator overload of [] that is defined in the base class of “this”. The base class is a defined class “Vector”. I don’t understand this line of code.
When in doubt, simplify.
First step:
return (*(Vector *)this)[i];
can be
Vector* ptr = (Vector*)this;
return (*ptr)[i];
Second step:
return (*ptr)[i];
can be
Vector& ref = *ptr;
return ref[i];
Both simplifications put together, the line
return (*(Vector *)this)[i];
is equivalent to
Vector* ptr = (Vector*)this;
Vector& ref = *ptr;
return ref[i];
When the member function is a const member function, this is of type Vector const* const.
The first line removes the const-ness of the object pointer.
The second line dereferences the pointer.
The last line returns the i-th element of the object.
I don’t understand this line of code.
return (*(Vector *)this)[i];
Assuming T is a type, T* is the type "pointer to T". Thus given that Vector is a type, Vector* is a pointer to Vector.
this is a special name which is a pointer to the object argument of a member function.
(T)expr is an explicit type conversion. It performs one or combination of static cast, reinterpret cast or const cast on the expression, converting the value to the type T. In the expression (Vector *)this, the this pointer is converted to the type Vector*. Given that Vector is a base class, this is a static cast, and more specifically, an up cast because we are casting up in the inheritance hierarchy.
The unary operator * in *expr is the indirection operator. It indirects through the pointer (in this case) operand and results in an lvalue of the pointed object. Thus, *(Vector *)this will be an lvalue of type Vector that is the base class sub object of this.
expr[index] is the subscript operator. Thus, (*(Vector *)this)[i] invokes the subscript operator of the base class on this object.
Finally, return expr; statement jumps out of the function, and returns the value of the expression to the caller. Thus, return (*(Vector *)this)[i]; returns the result of the base class' subscript operator.

Regarding definition of dereferencing and member selection operators in smart pointer

In smart pointer implementation, dereferencing operator and member selection operators are always defined as below.
T& operator* () const // dereferencing operator
{
return *(m_pRawPointer);
}
T* operator->() const // member selection operator
{
return m_pRowPointer;
}
I don't quite understand why the former is returned by reference, the latter is returned by pointer. Is it just to differentiate them or some other reasons?
To be more specific, can I make dereferencing operator returns by pointer, while the other one returns by reference?
why the former is returned by reference
So that the expression *thing gives an lvalue denoting an object of type T, just as it would if thing were a pointer.
the latter is returned by pointer
Because that's how the language is specified. Note that you never use the result of -> directly, but always in an expression of the form thing->member.
If thing is a class type, that's evaluated by calling operator->, then applying ->member to the result of that. To support that, it must return either a pointer, or another class type which also overloads operator->.
can I make dereferencing operator returns by pointer
Yes, but that would be rather confusing since it would behave differently to applying the same operator a pointer. You'd have to say **thing to access the T.
while the other one returns by reference
No, because that would break the language's built-in assumptions about how the overloaded operator should work, making it unusable.
The reason that the dereference operator returns by reference and the member selection operator returns by pointer is to line up the syntax of using a smart pointer with the syntax of using a raw pointer:
int* p = new int(42);
*p = 7;
std::unique_ptr<int> p(new int(42));
*p = 7;
You could absolutely make your dereference operator return anything you like:
struct IntPtr {
int* p;
int* operator*() { return p; }
};
But that would be pretty confusing for your users when they have to write:
IntPtr p{new int{42}};
**p = 7;
The arrow operator is a little different in that [over.ref]:
An expression x->m is interpreted as (x.operator->())->m
So you have to return something on which you can call ->m, otherwise you'll just get an error like (from gcc):
error: result of 'operator->()' yields non-pointer result

Clarification on smart pointer's operator* and operator-> overloading

it's passed a lot since i used c++ so here the(probally dumb) question:
A basic smart pointer Object should behave like a normal pointer one, so in a typical implementation we add the * and -> operator to the object, something like this:
template <class T> class auto_ptr
{
T* ptr;
public:
explicit auto_ptr(T* p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
T& operator*() {return *ptr;}
T* operator->() {return ptr;}
// ...
};
Now, in my knowings, the c++ * operator (dereference) stands for: "get the value pointed in the heap by the value of ptr" (is it right?), and the type of *ptr should be T. So why we would return an address?
T& operator*() {return *ptr;}
Instead of:
T operator*() {return *ptr;}
Second, by having the following snippet:
void foo()
{
auto_ptr<MyClass> p(new MyClass);
p->DoSomething();
}
Now, how can i access ptr->DoSomething() method by just writing p->DoSomething()? Logically i would come writing the wrong code:
p->->DoSomething();
Because p-> returns a T* and then i need another -> operator for access the DoSomething() method.
Thanks for any answer/clarification and sorry for eventually bad English.
In C++, when you evaluate a function, you end up with a value (unless the function's return type is void). The type of a value is always an object type. So when you say f(), that expression is a value of type T. However, there are different categories of value:
T f(); => f() is a prvalue, passed along by copy
T & f(); => f() is an lvalue, the same object that is bound to "return"
T && f(); => f() is an xvalue, the same object that is bound to "return"
So if you want a function to produce an existing value that you don't want to copy, you have to declare the return type of the function as one of the reference types. If the return type is not a reference type, then a copy of the return value will be made, and the caller only ever sees that copy.
The dereference operator returns a reference because then you can do e.g.
*somePointer = someValue;
and the value of what somePointer points to would change to someValue. If you returned by value, the above expression would have a temporary value that is assigned to, and then that temporary value is destructed and the change is lost.
The reason you don't have to write p->->DoSomething is that operator-> recurses until it finds something that isn't a pointer, T*.
p-> finds T* which is a pointer so it goes down another level and finds a MyClass-object, so it stops and does a normal operator. on that.
Note that smart pointers aren't considered pointers in this case.

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).