I have problem in this line std::cout << &X::a << std::endl; this line print 1 supposed to printed address of &X::a
this my code
#include <iostream>
#include <string>
#include <iomanip>
class X
{
public:
int a;
void f(int b);
};
void X::f(int b)
{
std::cout << "the value of b is " << b << std::endl;
}
void add()
{
std::cout << "Hello this function hello" << std::endl;
}
int main()
{
void (*funcPtr)(void) = add;
funcPtr();
int X::*ptrnumber = &X::a;
void (X::*ptrfunction)(int) = &X::f;
X xobj;
xobj.*ptrnumber = 10;
std::cout << "the vslue of a is " << xobj.*ptrnumber << std::endl;
(xobj.*ptrfunction)(20);
std::cout << std::hex << &X::a << std::endl;
//std::cout << funcPtr << std::endl;
}
i compiled with different complier c++ but i have same output
i displayed type of this "M1Xi" i don't know this data type
The expression
&X::ais not an address that you could use in an ordinary address. It is a relative address to a member. It can only be used with a pointer to member.Pointer to members can be converted to other pointer to members and only with constraints. They cannot be converted to other kind of pointers or to int. It is difficult in this condition to print their value.
The only conversion possible is to a boolean, and it is meant to see if it is null or not. Because a pointer to member can be nullptr:
If you want to print the address of the pointer to member, you must dereference it with an object:
As you may imagine, it is not possible to use tricks using dereferencing a nullptr to member or using a nullptr as object address, since dereferencing a null pointer is UB. By the way, this is not a real problem, because the standard makes very little guarantees about the layout of an object, so that this relative address is of little use on its own.