A static function can be called in relation to a particular object by a statement such as the following:
aBox.Afunction(10);
The function has no access to the non-static members of aBox. The same function could also be called without reference to an object. In this case, the statement would be:
CBox::Afunction(10);
where CBox is the class name. Using the class name and the scope resolution operator tells the compiler to which class Afunction() belongs."
Member functions act on a certain object. This object is referred to as the this pointer.
1 2 3 4 5
std::string foo = "some text";
int len = foo.length(); // calling member function 'length'
// whose length are we getting? "foo"'s length!
// foo becomes 'this' inside the length function
Conversely, static member functions are "this-less"... in that they do not act on a single object, but rather act on the class as a whole.
So you cannot access a non-static member from a static function because there's no object to act on.
1 2 3 4 5 6 7 8 9 10 11 12 13
class MyString
{
public:
int length() // non-static ... we have a 'this' object
{
return this_strings_length;
}
staticvoid foobar() // static... there is no 'this' object
{
int what = length(); // This is nonsense. Whose length are we getting?
}
};