Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of "this" in c++? [duplicate]

Tags:

c++

struct Foo
{
 void f()
 {
 // (*)
 }
};

What is the type of "this" in the line marked with (*) ?

Is it const Foo* or Foo* ?

like image 804
Adam Varhegyi Avatar asked Jun 17 '13 11:06

Adam Varhegyi


3 Answers

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

like image 179
ForEveR Avatar answered Nov 15 '22 12:11

ForEveR


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.

like image 31
Kaz Avatar answered Nov 15 '22 13:11

Kaz


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*

like image 3
dlmeetei Avatar answered Nov 15 '22 13:11

dlmeetei