pointer to member function in C++

109 views Asked by At

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

2

There are 2 answers

0
Christophe On

The expression &X::a is 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:

int X::*px = &X::a;
bool bx = px; std::cout << bx <<std::endl; 
px = nullptr; 
bool bn = px; std::cout << bn <<std::endl; 

If you want to print the address of the pointer to member, you must dereference it with an object:

std::cout << std::hex << &(xobj.*(&X::a)) << std::endl; 

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.

3
user17732522 On

&X::f and &X::a are not pointers. Because f and a are both non-static members, they are instead member pointers, which behave very differently from pointers regardless of the naming and syntax similarity.

A member pointer (whether function or data member) does not represent an address. So it doesn't make sense to try to print its address.

So there is also no overload for << with std::ostream in the standard library that would take a member pointer either.

However, there is an overload taking a bool as parameter and it is possible to implicitly convert a member pointer to bool. The result is false if the member pointer has the null member pointer value and true otherwise. With the default setting true is then printed as 1.