The c++ standard (ISO c++11) mentions in Section 9.3.1 that
A non-static member function may be called for an object of its class type, or for an object of a class derived (Clause 10) from its class type, using the class member access syntax (5.2.5, 13.3.1.1).
An attempt to compile this code with g++ (version 4.8.2)
class foo{
public:
void bar(){
cout<<"hey there"<<endl;
}
};
int main(){
foo obj;
foo::bar(&obj);
}
gives a compile time error because it couldn't match the function's signature. I guess that is expected given what the standard states about calling member functions. Since the method will eventually take a form similar to bar(foo*) during some stage of compilation, why does the standard asks for member access syntax to call the member function?
Lets add a static member to the class as:
Now if you write this:
Which function should be called? In such situation, how would you call both of them? What would be the syntax? If you allow one function to have this syntax, you've to abandon it (i.e syntax) for other function. The Standard decided to have foo::bar(&obj) syntax for
static
member function, while abandoning it for non-static member function.Anyway, if you want to pass
&obj
as argument to the non-static member function, then you can use type-erasure facilitated bystd::function
as:Likewise, you could call static member function as:
Note that at lines
#1
and#2
, the types of the objectpbar
makes the compiler to choose the correct member function — in the first case, it takes the pointer to the non-static member-function while in the latter case, it takes the pointer to the static member function.Hope that helps.