Reputation: 95
Consider the following code:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A(int _x) { x = _x; }
int get() { return x; }
};
class B
{
static A a;
public:
static int get()
{ return a.get(); }
};
int main(void)
{
B b;
cout << b.get();
return 0;
}
My doubt here pertains to this line of code:
public:
static int get()
{ return a.get(); }
As per this link: Why can I only access static members from a static function?, a static
function can only access a static
data member. However, in this function, we are returning a.get()
. The function get()
in class A
, returns x
, which is a non-static
variable. So, does this not contradict the fact that static function can only access static data members?
Please guide.
Upvotes: 2
Views: 781
Reputation: 8171
You're trying to read too much into the simple statement of "static functions can only access static members". It isn't meant to say that there is some kind of overall ban on static functions touching any instance data in any way. (What purpose would such a thing serve anyway?)
Think about static functions as more similar to functions not associated with a class at all. You could do things like:
int foo()
{
A a;
return a.get();
};
or
A a;
int foo()
{
return a.get();
};
Or other variations, and it's fine. So too with static functions.
We could perhaps re-word things more like "accessing instance members requires having an instance to access them from, while static functions can be called without an instance and therefore do not have instance members inherently available", but that's a lot more words and probably not as clear for answering the common beginner question of why they can't access the members of their class from a static function.
Upvotes: 2
Reputation: 118300
a static function can only access a static data member.
This is correct.
However, in this function, we are returning a.get().
Yes, and because a
is a static data member, the requirements for accessing only a static data member are met.
The End.
Really, that's it. That's the end of the story. What happens inside get()
does not matter any more, and whether what's happening in get()
is well-formed, or ill-formed, will stand on its own merits.
get()
is not a static
class member, but that's not where the static-only rule applies. The static-only rule applies to a
, because that's the static member of B
, and not a.get()
. get()
is a non-static member of A
, and for that reason it won't have any difficulties, whatsoever, accessing non-static members of its own class.
The rule is: a static member can only access other static members of its class. The rule is not: a static member can only access other static members of its class, and only their own static members of those classes, in turn, and only the static members of those classes, as well, in perpetuity.
Upvotes: 1