if this
is a const pointer to class's object how can you return a const pointer from non-const return type?
Class T
{
public:
T* func(){return this;}
};
Firstly, this
is not a "const pointer". Where did you get that strange idea? Pointer this
has scalar type and is not an lvalue, meaning that it can't possibly be "const" or "non-const". Pointer this
is an rvalue and it is non-modifiable.
Secondly, the code in your question is valid regardless of whether the pointer involved is const or not. For example, the following code is valid for exactly the same reason
int *const p = 0; /* a const pointer */
int *foo() {
return p; /* OK, no error here */
}
What is returned in this case is a completely independent copy of the original pointer value. It does not matter whether p
is const or not - making a copy of const value does not in any way violate its constness.
This is exactly what's done in your code sample - you are returning a copy of this
's value. Why would you even care whether this
is const or not?
Unless the member function is const-qualified (e.g. T* func() const
instead of just T* func()
), this
is of type T*
.
this
is not itself modifiable (so you can't assign something to this
), but it's just a pointer to an object of type T
like any other and can be used as such.
AndreyT provided the explanation and here is the reference.
From standard docs 9.3.2.1 The this pointer,
In the body of a non-static (9.3) member function, the keyword this is an rvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
which explains the question that you asked and the comment you made to AndreyT.
Hope this one also helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With