Hi, I was wondering how to reference non static variables from within a static function. Do you have to recast them as static within the function? I'm completely new at static programming, so if anyone has any good tutorials it would be much appreciated.
The reason originates at what happens when a class is instantiated.
When a class is instantiated, memory is allocated for the non-static data members.
That means when a class is not instantiated, no memory is allocated for the non-static data members and hence they cannot be accessed.
A non-static method can access non-static data members.
So non-static methods can only be called after a class is instantiated.
Now static methods can be called without instantiating the class.
So if a static method calls a non-static method which in turn accesses non-static data members and the class is not instantiated, you're trying to access invalid memory.
«_Superman_» I love work. It gives me something to do between weekends.
You'll have to pass a pointer to the particular object you want to access into the method.
Let's say you have a class called Car, with a non-static member "color" and a static method "carsSoldAtDealership()". The latter is clearly not meant to apply to any particular Car object; it simply related to them, and is thus included in the class. If you tried to access the "color" field within carsSoldAtDealership(), which Car are you interested in the color of? It doesn't make sense to ask the question.
If you also had a static method "computeTimeOfNextService(Car *c)", then you could pass a pointer to a Car into the method and it would then be able to access that Car's private fields since it's a class member. Of course, you could equivalently make this a non-static method taking no parameters, so that which Car it is operating on is implicit.
Last edited by Lindley; July 2nd, 2009 at 01:00 PM.