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.
get()itself is notstatic, right? Do you understand the reason whystaticfunctions can't access non-staticdata members?A::get, which is called when you doa.get().ais astaticinstance, it is an instance. And, of course, you can access non-static members of that instance. Static member functions may be called without an instance. Hence, there is no validthispointer and non-static members are not accessible due to the lack of an instance i.e. a validthispointer. But that doesn't apply to astaticinstance of a class.