Do static functions have access to non static data members of a class?

From my book:

"A static function might have this prototype:

static void Afunction(int n);

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

Why exactly cant Afunction access non-static members?
CBox::Afunction(10); ¿members of which object do you want access to?
aBox.Afunction(10);

This form is not recommended because it is a nonsensical use of static functions.
I dont but it is possible right or nope?

Also @LB What do you mean?
Anmol444:

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

    static void foobar()  // static... there is no 'this' object
    {
        int what = length();  // This is nonsense.  Whose length are we getting?
    }
};
Last edited on
Oooh good point. Thanks :D but can I use this: classname.member?
There's a difference between the class and the object.

An object is an instance of the class. IE:

 
std::string foo;


string is the class.... foo is the object.

The "dot" operator (.) needs an object... not a class:

1
2
3
string.length(); // nonsense

foo.length();  // makes sense.  getting foo's length 


Static functions do not change this behavior. If you want to access a non-static member, you need an object.
Ok thanks :D
Topic archived. No new replies allowed.