I know in classes that each object's variables will have a different address in memory. However, member functions' addresses are common between objects, so only one function is loaded in memory with a common address.
The issue is I was trying to print the address of a certain member function of the class itself and I expected it to be the same as the member function's address of all objects. But I found that it's different from them!! That was very strange for me.
#include<iostream>
using namespace std;
class LuckyNum {
public:
void PrintAddress() {
printf("\tFunction address :%p\n", &LuckyNum::PrintAddress);
}
};
int main() {
LuckyNum r1;
cout << "r1:\n";
r1.PrintAddress();
LuckyNum r2;
cout << "r2:\n";
r2.PrintAddress();
cout << "LuckyNum Class:\n";
printf("\tFunction address :%p\n", &LuckyNum::PrintAddress);
return 0;
}
/*Output!! :
r1:
Function address :0000007acdbffda0
r2:
Function address :0000007acdbffda0
LuckyNum Class:
Function address :0000007acdbffde0 => HOW!! it should equal the above two addresses, shouldn't it?
*/
The function call
invokes undefined behaviour.
printfis not typesafe, and&LuckyNum::PrintAddressis not a pointer. It is a pointer to member, which is a very different thing and it's representation is implementation defined. See the following program:The
getAddress()function stores the pointer to member&LuckyNum::getAddressin a vector of bytes and returns it.mainthen obtains one pointer to member via thegetAddress()function and another one directly via&LuckyNum::getAddress. Then it compares to the byte by byte and if you run the program (with gcc at least) you will find that the two pointers to member are indeed equal.