I try to find address of this
pointer, but this code is showing a strange
error:
#include <iostream>
using namespace std;
class Base
{
public:
void test()
{
void *address_of_this =&this;
cout<<address_of_this<<endl;
}
};
int main()
{ Base k;
k.test();
return 0;
} //error non-lvalue in unary'&'
Can you explain this error ?
Also point that what is illegal in taking address of this
?
example_class* address_of_object(void) { } : The return data type of this function is of a type pointer to the class object. The function does not require any parameters. The 'this' pointer used, returns the address of the current object, which is the class object that is used to call this function in main().
You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.
How do I print the address stored in the pointer in C++? int *ptr = &var; printf("%p", ptr); That will print the address stored in ptr will be printed.
- When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (ie the object on which the function is invoked). This pointer is known as 'this' pointer.
this
is a pointer containing the address to the "current object". It is not a variable that is stored somewhere (or could even be changed), it is a special keyword with these properties.
As such, taking its address makes no sense. If you want to know the address of the "current object" you can simply output:
std::cout << this;
or store as
void* a = this;
Quoting the 2003 C++ standard:
5.1 [expr.prim] The keyword
this
names a pointer to the object for which a nonstatic member function (9.3.2) is invoked. ... The type of the expression is a pointer to the function’s class (9.3.2), ... The expression is an rvalue.5.3.1 [expr.unary.op] The result of the unary
&
operator is a pointer to its operand. The operand shall be an lvalue or a qualified_id.
To put it simply, &
requires an lvalue. this
is an rvalue, not an lvalue, just as the error message indicates.
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