Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static functions vs const functions

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?


2 Answers

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.

like image 90
Uri Avatar answered Sep 09 '25 22:09

Uri


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?"

like image 20
Richard Avatar answered Sep 09 '25 22:09

Richard