Followers 0

## 15 posts in this topic

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

##### Share on other sites
I think I'm starting to understand. Thanks!
0

##### 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.
1

##### 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.
0

##### 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
-2

##### 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.
2

##### 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
-2

##### 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.
0

##### 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.)
0

##### 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.
0

##### 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#.
0

##### 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.
0

##### 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.
2

##### Share on other sites
@Cornstalks
Thank you por pointing that out and for complementing this topic.

Sorry for the C++ code as well.
2

## Create an account

Register a new account