views:

110

answers:

2

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?

+7  A: 

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.

Uri
Yeah. I talked to my co-workers and we came to the same thought. Thanks.
baash05
+1  A: 

If a member function doesn't use any of the member variables it is often worth asking the question:
"Does this need to be a member function in the first place?"

Richard