Static functions vs const functions

baash05 picture baash05 · Mar 30, 2010 · Viewed 9.3k times · Source

I'm looking at a member function

int funct(int x) const; 

And I'm wondering if

static int funct(int x); 

would be better.

If a member function doesn't use any of the member variables should it be static. Are there any things that would discourage this?

Answer

Uri picture Uri · Mar 30, 2010

Assuming this is C++, a function declared as const indicates that it does not intend to change data members on the instance on which it is called, i.e., the this pointer. Since there are ways to evade this, it is not a guarantee, merely a declaration.

A static function does not operate on a specific instance and thus does not take a "this" pointer. Thus, it is "const" in a very naive way.

If your method does not need to be bound to a specific instance, it makes sense to make it static.

However, if your method is polymorphic - that is, you provide a different implementation based on the instance of the object on which it is invoked, then it cannot be static, because it does depend on a specific instance.