About the address of member function

S

Sharpdew

class Test
{
double i;

public:
void fun(){}
void foo(void)
{
cout << "as";
}
};

int main()
{
Test t;
t.foo; // mean what?
Test::foo; // mean what?

cout << &Test::foo << endl; // output 1, why?
cout << &Test::fun << endl; // output 1, too, why?

return 0;
}
 
B

benben

Sharpdew said:
class Test
{
double i;

public:
void fun(){}
void foo(void)
{
cout << "as";
}
};

int main()
{
Test t;
t.foo; // mean what?
Test::foo; // mean what?

The last two expressions mean nothing. They are illegal. You can make a
call:

t.foo()

Or take the address of the function:

&Test::foo
cout << &Test::foo << endl; // output 1, why?
cout << &Test::fun << endl; // output 1, too, why?

return 0;
}

Pointer to members are not really memory address in the strict sense.
You can think of it as a relative address (to whatever instance of that
type.)

Therefore, pointer to member cannot be converted to a normal pointer,
say, void*. Therefore it is not outputted as a normal pointer.

If you are so interested in the bit sequence of these pseudo pointers
you can do a forced conversion using reinterpret_cast, like so:

int main()
{
typedef void (Test::*tf)(void);

tf p1 = &Test::foo;
tf p2 = &Test::fun;

cout << *reinterpret_cast<void**>(&p1) << endl;
cout << *reinterpret_cast<void**>(&p2) << endl;
}
 
S

Sharpdew

I'm sure know all you said, but what I want to know is the semantics of
these style code, that is to say, how do the compiler deal with them?
benben 写é“:
 
S

Sharpdew

I'm sure to know all you said, but what I want to know is the semantics
of
these style code, that is to say, how does the compiler deal with them?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top