Still confused about "static"

Started by
14 comments, last by kuramayoko10 11 years, 6 months ago
I am still perplexed by the use of the "static" keyword. I have read that a static method can be used without creating an instance of the class that contains it, but why is this beneficial? I think an example would really help my understanding. Also, what is the purpose of a declaring a variable as static when the method was not declared static (if there is a purpose)?
Advertisement
You can use static variable to count number of class's instances:

struct Foo {
static unsigned int instanceCounter = 0;
Foo() {
instanceCounter++;
}
~Foo() {
instanceCounter--;
}
};

Why would you need that is other question.

static method can be used in singleton pattern:

struct Foo {
static Foo& GetInstance() {
static Foo instance;
return instance;
}
};
I imply you are talking about C++ ...
Overloading "static" keyword is one example of the bad language design in part of C++ (it was partially inherited from C, but C++ made it much worse).

Ok, as of your questions:

One example of using static method is writing frontend to your object construction/fetching system:

class MyClass {
private:
MyClass (const char *id);
public:
// Either fetch existing object by id or create new if not present
static MyClass *newMyClass (const char *id);
};

MyClass *myobject = newMyClass ("somename");

There are different patterns to achieve that, but the example above has nice feature of keeping object construction interface inside class.

Another example are methods, that operate on multiple objects

class Vector {
public:
// Get the length of single vector
float length ();
// Dot product of two vectors
static float dot (const Vector& a, const Vector&b);
};

Now you could use "ordinary" method for "dot", but this has wrong implication that one of the "dot" components is somewhat special.

You also will use static methods as callbacks while interfacing with C libraries (and C++ code too if you want to avoid the mess with method pointers)

As of static variables, you have to make distinction between the ones declared inside class and the ones declared inside methods (scope).
If you declare variable static inside method, it makes this variable persistent between different calls to the same method (both for "ordinary" and static methods. It can be used, for example, in following pattern:

void myMethod () {
static bool warned = false;
if (some_error_condition && !warned) {
// Warn user
warned = true;
}
}


Static variables declared in class are simply global variables that are associated with class (i.e. acces privileges, namespacing etc.).
Lauris Kaplinski

First technology demo of my game Shinya is out: http://lauris.kaplinski.com/shinya
Khayyam 3D - a freeware poser and scene builder application: http://khayyam.kaplinski.com/
I think I'm starting to understand. Thanks!
The way I see it, a static member function is the same as a standalone function, except it is in the namespace of the class and it has access to private and protected parts of the class.

I don't use them much, probably because I grew up with standalone functions and find them more natural.

The way I see it, a static member function is the same as a standalone function, except it is in the namespace of the class and it has access to private and protected parts of the class.

I don't use them much, probably because I grew up with standalone functions and find them more natural.


This is how I view them too, they're basically a mechanism for writing procedural-style functions in an OO environment.

The static keyword sees a lot of abuse though, exactly because they encourage this procedural-style programming in pure OO environments, and one could argue about whether they actually make sense at all in OOP. There are quite some anti-patterns which are based off of this abuse of the static keyword (like the singleton pattern), so be careful when using it.

I try not to use the static keyword except for cases where they naturally fit as a solution to a problem I'm trying to solve. A good example would be the one Lauris Kaplinski provided about creating instances of a class, as this can come in handy if you work with some exotic allocation mechanism but don't want to override the default new operator for example.

I gets all your texture budgets!


The way I see it, a static member function is the same as a standalone function, except it is in the namespace of the class and it has access to private and protected parts of the class.

I don't use them much, probably because I grew up with standalone functions and find them more natural.


Just to make your response a bit more clear to the OP.
From a static method you can only access static variables from your class. This make sense since the method is in the scope of class and so are the static variables. All the other variables are in the scope of object and therefore cannot be accessed, initialized, etc.
Programming is an art. Game programming is a masterpiece!

[quote name='alvaro' timestamp='1349616657' post='4987666']
The way I see it, a static member function is the same as a standalone function, except it is in the namespace of the class and it has access to private and protected parts of the class.

I don't use them much, probably because I grew up with standalone functions and find them more natural.


Just to make your response a bit more clear to the OP.
From a static method you can only access static variables from your class. This make sense since the method is in the scope of class and so are the static variables. All the other variables are in the scope of object and therefore cannot be accessed, initialized, etc.
[/quote]

That doesn't make it any more clear: It makes it false.

A static method has access to all parts of the class. What it doesn't have is a `this' pointer, but if it handles any instances of the class, it has full access to those instances, not only through the public interface. Think of the `dot' example that Lauris posted above.

A static method has access to all parts of the class. What it doesn't have is a `this' pointer, but if it handles any instances of the class, it has full access to those instances, not only through the public interface. Think of the `dot' example that Lauris posted above.


Ah, I was just talking about basic (non-static) variables declared in the class.
Like in the following example:


#include <cstdio>
#include <cstdlib>
class MyClass
{
private:
int var1;
static int var2;
public:
MyClass()
{
var1 = 1;
}

static void printVar()
{
printf("var1: %d\n", var1);
printf("var2: %d\n", var2);
}
};

int MyClass::var2 = 2;

int main(int argc, char *argv[])
{
MyClass::printVar();

return 0;
}

The first printf() inside the printVar static method refers to a non-static variable declared in the class.
As result it yields the following error:
error: invalid use of member 'MyClass::var1' in static member function

If you comment that line, it will work fine with the static variable var2.

Just fixing my previous comment...
Programming is an art. Game programming is a masterpiece!
If this is C++, there are two separate overloads of the keyword static.

First, it can be used to indicate to the linker that a symbol is local only to the translation unit. You will see this use for functions and variables declared at namespace scope within implementation files (you can do it in a header file, but the result may not be what you intended). C++ purists avoid this use of the keyword static over using anonymous namespaces, but practical programmers know that it has distinct advantages at link and runtime due to the implicit extern linkage of non-static namespace-level symbols.

Second, the keyword static can be used a variable is of static storage duration, one of the three kinds of storage durations available in C++ (the others are automatic and free store). You will see this use when a variable is declared as a member of a class or as a "local" variable in a function body. You need to understand the three types of storage duration to begin to understand C++, it's of fundamental importance.

A static member variable is what other languages call a class variable, in that it does not belong to an instance of the class but instead one copy is shared among all instances of the class.

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement