struct Foo
{
void f()
{
// (*)
}
};
What is the type of "this" in the line marked with (*) ?
Is it const Foo* or Foo* ?
n3376 9.3.2/1
In the body of a non-static (9.3) member function, the keyword this is a prvalue 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*.
Inside f
, this
has type Foo *
because f
is not a const
member function.
You cannot call f
on a const Foo
object. The following is erroneous:
const Foo obj;
obj.f();
This is precisely because inside Foo::f
, the this
pointer is Foo *
rather than const Foo *
, and so the function call demands a pointer conversion which discards a qualifier.
The this
pointer itself is not a variable. It is not assignable, but not because of a const
qualifier. There is no declaration in scope such as Foo *const this
. A this
expression is simply not an lvalue, as a rule of the language.
The this
pointer is not very different from &obj
.
The type of this depends on the member function.
For example for a class X, if the member functions is
1) const, Then this is of type const X*
2) volatile, then this is volatile X* etc
otherwise it is X*
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