In a C++ class is there any overhead in having static function instead of a member functions.
class CExample
{
public:
int foo( int a, int b) {
return a + b ;
}
static int bar( int a, int b) {
return a + b ;
}
};
My questions are;
A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared. Suppose a static member function f() is a member of class X . The static member function f() cannot access the nonstatic members X or the nonstatic members of a base class of X .
Static function: Advantage: it could be called without existing real object. Static member functions become useful when you want the class as a whole to have a function, instead of each individual object. With a static member function, you can then change static variable data.
'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).
In this example is foo() or bar() more efficent?
No. Both calls are resolved statically. There may be some overhead in passing the this
pointer to a non-static
function, but in this case both will likely be inlined.
Why would I not want to make foo() in to a static function as it does not alter any member variables?
You wouldn't, it's actually good practice to make all methods not bound to an instance static
.
This answer focuses addresses the second part of your question
Quoted from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices:
Chapter 44. Prefer writing nonmember nonfriend functions
[...] Nonmember nonfriend functions improve encapsulation by minimizing dependencies [...]
Scott Meyers proposes the following algorithm for determining which methods should be members of a class (source)
if (f needs to be virtual)
make f a member function of C;
else if (f is operator>> or operator<<)
{
make f a non-member function;
if (f needs access to non-public members of C)
make f a friend of C;
}
else if (f needs type conversions on its left-most argument)
{
make f a non-member function;
if (f needs access to non-public members of C)
make f a friend of C;
}
else if (f can be implemented via C's public interface)
make f a non-member function;
else
make f a member function of C;
As for the first half of your question, I'd guess the compiler would optimize any difference away.
bar MAY have less overhead in some compilers/situations since it will never need to be placed in a pointer table and will not need an extra "this" parameter.
the only reason to make foo non-static if it does not use local memebers is if you intend to overload it, but since it is not virtual this does not come into play.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With