0

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?

1
  • 3
    you cannot have virtual static methods. Commented Aug 12, 2012 at 21:30

2 Answers 2

2

Memeber functions are are not created by instance. They have an implicit first parameter which is the this pointer, so they actually look quite similar to your static function.

For example,

struct Foo { void foo(int i) {} } Foo f; f.foo(42); Foo::foo(f, 42); 

the two last lines do the same. However, it is hard to see how one could implement this with static methods or functions:

struct IFoo { virtual foo() const {} }; struct Foo1 : virtual public IFoo { virtual foo() const {} }; IFoo* f = new Foo1; f->foo(); 

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, only the local variables are per instance when the method is called. The code is not duplicated, as juanchopanza says.
2

It's important because it allows polymorphism; specifically because it's needed for dynamic dispatch, where the method to which to bind the call is determined at runtime by the true type of the object on which it's invoked. A static call always binds to the method on the nominated type, regardless of the runtime type of the object itself.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.