Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Still confused about "static"


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
15 replies to this topic

#1 JDCAce   Members   -  Reputation: 146

Like
0Likes
Like

Posted 06 October 2012 - 02:09 AM

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

Sponsor:

#2 Ripiz   Members   -  Reputation: 529

Like
3Likes
Like

Posted 06 October 2012 - 02:45 AM

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;
    }
};


#3 Lauris Kaplinski   Members   -  Reputation: 841

Like
4Likes
Like

Posted 06 October 2012 - 03:24 AM

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/

#4 JDCAce   Members   -  Reputation: 146

Like
0Likes
Like

Posted 07 October 2012 - 12:51 AM

I think I'm starting to understand. Thanks!

#5 Álvaro   Crossbones+   -  Reputation: 13698

Like
1Likes
Like

Posted 07 October 2012 - 07:30 AM

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.

#6 Radikalizm   Crossbones+   -  Reputation: 2944

Like
0Likes
Like

Posted 07 October 2012 - 08:26 AM

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!


#7 kuramayoko10   Members   -  Reputation: 386

Like
-2Likes
Like

Posted 07 October 2012 - 09:46 AM

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.

Edited by kuramayoko10, 07 October 2012 - 09:47 AM.

Programming is an art. Game programming is a masterpiece!

#8 Álvaro   Crossbones+   -  Reputation: 13698

Like
2Likes
Like

Posted 07 October 2012 - 12:13 PM


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.


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.

#9 kuramayoko10   Members   -  Reputation: 386

Like
-2Likes
Like

Posted 07 October 2012 - 01:12 PM

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

Edited by kuramayoko10, 07 October 2012 - 01:12 PM.

Programming is an art. Game programming is a masterpiece!

#10 Bregma   Crossbones+   -  Reputation: 5251

Like
0Likes
Like

Posted 07 October 2012 - 01:48 PM

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

#11 SiCrane   Moderators   -  Reputation: 9630

Like
0Likes
Like

Posted 07 October 2012 - 01:54 PM

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

#12 ChaosEngine   Crossbones+   -  Reputation: 2477

Like
0Likes
Like

Posted 07 October 2012 - 06:42 PM

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


Nope, I see it too.
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

#13 Álvaro   Crossbones+   -  Reputation: 13698

Like
0Likes
Like

Posted 07 October 2012 - 08:43 PM

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

I carefully ignored it. I apologize for any confusion I might have created: I know nothing about C#.

#14 krippy2k8   Members   -  Reputation: 646

Like
0Likes
Like

Posted 07 October 2012 - 09:56 PM

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


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.

#15 Cornstalks   Crossbones+   -  Reputation: 6991

Like
2Likes
Like

Posted 07 October 2012 - 10:49 PM


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:
[...]

You missed alvaro's point. Consider the following:

#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();
}

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:
// 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()
{
}
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.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#16 kuramayoko10   Members   -  Reputation: 386

Like
2Likes
Like

Posted 08 October 2012 - 09:55 AM

@Cornstalks
Thank you por pointing that out and for complementing this topic.

Sorry for the C++ code as well.
Programming is an art. Game programming is a masterpiece!




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS