Why would I use a member function when I can pass a static function a reference to an object?
For example:
#include <iostream>
class Widget{
private:
int foo;
public:
Widget(){
foo = 0;
}
static void increment( Widget &w ){
w.foo++;
std::cout << w.foo << std::endl;
}
};
class Gadget{
private:
int foo;
public:
Gadget(){
foo = 0;
}
void increment(){
foo++;
std::cout << foo << std::endl;
}
};
int main(int argc, const char * argv[]){
Widget *w = new Widget();
Widget::increment( *w );
Gadget *g = new Gadget();
g->increment();
return 0;
}
Is this more than a stylistic thing? My understanding is that member functions are created per object instance, while static functions are not — and since you can make static functions operate on a per instance basis like in the above example, shouldn’t it slightly more efficient to create static functions instead of member functions?
Memeber functions are are not created by instance. They have an implicit first parameter which is the
thispointer, so they actually look quite similar to your static function.For example,
the two last lines do the same. However, it is hard to see how one could implement this with static methods or functions:
So, besides the syntactic sugar of allowing you to call the methods on an instance with the
.operator, you need them for this kind of run-time polymorphism.