Why the ppp1 is NULL and no compiler's warning nor error? Code: class Test2 { static void Func1(int* a, int b) { } static void Func1(void* a, int b) { } }; class Test { public: static void Func1(int* a, int b) { } static void Func1(void* a, int b) { } }; void* Do2() { //return (void(*)(int*,int)) &Test2::Func1; return &Test2::Func1; } void* Do() { return (void(*)(int*,int)) &Test::Func1; } int _tmain(int argc, _TCHAR* argv[]) { void* ppp1 = Do(); return 0; }
You have not instantiated an object of type Test2. There is no requirement for the compiler to generate and locate its methods. I suspect that you are thinking that the static keyword will force that. The static keyword need only force the method of access WHEN the method is ultimately generated, if ever. You might find some compiler (particularly an older one) that will generate and locate that method, despite the fact that the object doesn't exist. That would not be a robust implementation. Your very own code would result in an item whose use would result in undefined behavior. I haven't read the standard with regard to whether or not a compliant compiler should issue a warning or error. If you get a NULL value and are a competent programmer, you will not attempt to dereference it, right? You may, after all, write this statement, and compile without error: Code: void *myPtr = NULL; Would you attempt to use that pointer?
Even if I instantiated the Test2 class, nothing change. I would expect something like 'cannot convert from overloaded-function to void*' or 'mismatch in formal parameter list'. My problem is that there are two versions of 'Func1'. If I modify the code to use the 'Func1' without the class 'Test2', I get a compiler error (mismatch...).
Code: void* Do2() { //return (void(*)(int*,int)) &Test2::Func1; [COLOR=Red]1[/COLOR] return &Test2::Func1; [COLOR=Red]2[/COLOR] } How would you expect the compiler to resolve the ambiguity inherent in statement 2, anyway??? Why did you deep-six statement 1? Could YOU, a sentient being, resolve the ambiguity without a hint??? Exactly what is your purpose in your approach?
As I wrote in my post, I would expect that the compiler notify me (by error or warning) about the problem. My point (question) is: why is the compiler able to notify me about the problem if both 'Func1' are outside the Test2 class or if I move the code from Do2 function to the main.