Reputation: 361
I have learned that function name equals function address like this:
void func(){}
void main() { cout << func; }
But when I used the same code to print memeber function, it went wrong.
class Test{
public:
void func() {}
void printFunc1() {
cout << func << endl;
}
void printFunc2() {
void (Test::*ptrtofn)() = &Test::func;
cout << (void*&)ptrtofn << endl;
}
};
printFunction2()
work but printFunction1()
doesnt
What makes the difference?
Member function's name is not member function's address? Is there any reason?
Upvotes: 3
Views: 184
Reputation: 965
Please understand "func" is the member function of the class . accessing it directly is itself a compilation error .Rather you should try to use pointer to member function as you have done in printFunction2: Else if func is function outside the class scope .Then it can be done as below :
#include <iostream>
using namespace std;
void func() {cout<<"\n calling func\n";}
void printFunc1() {
cout << endl<<hex<<(void*)func << endl;
}
int main() {
printFunc1();
return 0;
}
Upvotes: 0
Reputation: 8785
member function != standalone function
Only standalone functions can be converted to pointer implicitely.
4.3 Function-to-pointer conversion [conv.func]
1 An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function. 5858) This conversion never applies to non-static member functions because an lvalue that refers to a non-static member function cannot be obtained.
Upvotes: 5