do you recommend making all member functions
static that do not change the state of a class?
First you use the word "class" when I think you may have ment
"object". Think of class as "the cookie cutter" and object as "the
cookie".
Second, just because a member function does not change the state of an
*object* does not mean it can be static.
Here is a general rule of thumb you could try:
- Member functions that do not use (read or write) the state of the
object can be static. (There is no "the object")
- Member functions that want to know, but not change, the state of the
object can be const.
- Member functions that need to change the state of the object should
be non-static non-const.
Example pseudocode:
class Color
{
private:
int red;
int green;
int blue;
public:
Color(int red, int green, int blue) :
red(red),
green(green),
blue(blue)
{
}
// neither const nor static because it modifies member variables
void set_color(int red, int green, int blue)
{
this->red = red;
this->green = green;
this->blue = blue;
}
// const because it only reads from member variables
void get_color(int & red, int & green, int & blue) const
{
red = this->red;
green = this->green;
blue = this->blue;
}
// static because it doesn't use any non-static functions or
variables
// i.e. it is related to the Color concept, but not to any
existing Color object
static Color get_black()
{
return Color(0,0,0);
}
};
Now, there are things called "static member variables". These are not
part of any particular object, although you might think of them as
part of "the state of the *class*". These can be read/written by
static member functions, const member functions, and non-const/non-
static member functions. Also (depending on the access) these can be
read/written by non-member functions and member functions from other
classes.
Also one more clarification for static member functions: when I saw
that they "can't use non-static member functions or variables", by
this I mean that they cannot use such things directly (because there
is no "this" object). They can however use such things indirectly,
i.e. through an object of the class. For instance our Color class
might have another static member function called get_white:
static Color get_white()
{
// For demonstration purposes here, assume Color
// has only a default constructor:
Color c;
c.set_color(255, 255, 255); // ok to call set_color because it is
indirect
return c;
}
The same thing with const member functions. They can modify the state
of other objects, just not there own. e.g.:
bool Color::isBlackOrWhite() const
{
// For this assume I have an equality operator defined
Color compare_color = make_black();
if(*this == compare_color)
{
return true;
}
compare_color.set_color(255, 255, 255); // ok to call non-const
function because it is not us
return *this == compare_color;
}