• Advertisement
Sign in to follow this  

Still confused about "static"

This topic is 1928 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
You can use static variable to count number of class's instances:
[CODE]
struct Foo {
static unsigned int instanceCounter = 0;
Foo() {
instanceCounter++;
}
~Foo() {
instanceCounter--;
}
};
[/CODE]
Why would you need that is other question.

[i]static[/i] method can be used in singleton pattern:
[CODE]
struct Foo {
static Foo& GetInstance() {
static Foo instance;
return instance;
}
};
[/CODE]

Share this post


Link to post
Share on other sites
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:
[code]
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");
[/code]
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
[code]
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);
};
[/code]
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:
[code]
void myMethod () {
static bool warned = false;
if (some_error_condition && !warned) {
// Warn user
warned = true;
}
}
[/code]

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[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.
[/quote]

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.

Share this post


Link to post
Share on other sites
[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.
[/quote]

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. Edited by kuramayoko10

Share this post


Link to post
Share on other sites
[quote name='kuramayoko10' timestamp='1349624767' post='4987700']
[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.
[/quote]

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.

Share this post


Link to post
Share on other sites
[quote name='alvaro' timestamp='1349633597' post='4987729']
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.
[/quote]

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

[CODE]
#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;
}
[/CODE]
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... Edited by kuramayoko10

Share this post


Link to post
Share on other sites
If this is C++, there are two separate overloads of the keyword [i]static[/i].

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 [i]static[/i] over using anonymous namespaces, but practical programmers know that it has distinct advantages at link and runtime due to the implicit [i]extern[/i] linkage of non-static namespace-level symbols.

Second, the keyword [i]static[/i] can be used a variable is of [i]static storage duration[/i], one of the three kinds of [url="http://en.cppreference.com/w/cpp/language/storage_duration"]storage durations[/url] 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.

Share this post


Link to post
Share on other sites
Am I the only one seeing the C# tag on this thread? (This is not a rhetorical question, I'm severely confused by the number of C++ specific responses here.)

Share this post


Link to post
Share on other sites
[quote name='SiCrane' timestamp='1349639685' post='4987759']
Am I the only one seeing the C# tag on this thread? (This is not a rhetorical question, I'm severely confused by the number of C++ specific responses here.)
[/quote]

Nope, I see it too.

Share this post


Link to post
Share on other sites
[quote name='SiCrane' timestamp='1349639685' post='4987759']
Am I the only one seeing the C# tag on this thread? (This is not a rhetorical question, I'm severely confused by the number of C++ specific responses here.)
[/quote]
I carefully ignored it. I apologize for any confusion I might have created: I know nothing about C#.

Share this post


Link to post
Share on other sites
[quote name='SiCrane' timestamp='1349639685' post='4987759']
Am I the only one seeing the C# tag on this thread? (This is not a rhetorical question, I'm severely confused by the number of C++ specific responses here.)
[/quote]

There is no C# "prefix" so I guess most people - like me - don't really look at the tags and just assume that every question is C++ unless the OP mentions another language in their question, especially when the topic is something that is essentially the same in most languages anyway.

Share this post


Link to post
Share on other sites
[quote name='kuramayoko10' timestamp='1349637120' post='4987744']
[quote name='alvaro' timestamp='1349633597' post='4987729']
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.
[/quote]

Ah, I was just talking about basic (non-static) variables declared in the class.
Like in the following example:
[...]
[/quote]
You missed alvaro's point. Consider the following:

[CODE]
#include <iostream> // this is C++... let's use C++, not C
class MyClass
{
private:
int var1;
static int var2;
public:
MyClass()
{
var1 = 1;
}

static void printVar()
{
MyClass mc;
std::cout << "var1: " << mc.var1 << std::endl; // Look, I can access private members!
std::cout << "var2: " << var2 << std::endl;
}
};

int MyClass::var2 = 2;

int main()
{
MyClass::printVar();
}
[/CODE]

I'm sorry to further digress from C#, but I feel like this should be further expanded for future readers. The following is C/C++ specific, and the majority of what other people before me have said apples to C#. Bregma pointed out an important effect of the static keyword in C++: "it can be used to indicate to the linker that a symbol is local only to the translation unit." People so far have talked about variables and class member methods, but no one has talked about global/non-class methods. But it also applies to global methods. Consider:
[code]
// there is a static modifier on foo, so its symbol exists only in the current source file
// (i.e. you can't call it from another source file, even if you put "extern void foo();" in that
// source file)
static void foo()
{
}

// there is no static modifier for bar, so its symbol is visible from other translation units
// (i.e. in another source file, you can do "extern void bar();" and then call bar())
void bar()
{
}
[/code]
A further implication of this is that if you have two functions, both named foo(), that do completely different things and are just "helper" functions for a particular source file, you should declare them both "static" or else their symbols will conflict with each other, even though they're not in the same source file! Moral of the story: always make global/non-member functions static, unless you explicitly want them to be available in other translation units (and expect its name to be unique by all who consume your code). This is one aspect where namespaces are so useful.

Sorry for the digression. Now I feel like the discussion on static in C++ is complete, and hopefully we can all get back to focusing on C# and the OP.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement