Can a Static method access a private method of the same class?

Flowing Cloud picture Flowing Cloud · Aug 25, 2016 · Viewed 25.4k times · Source

I have this question because of the singleton/named constructor. In both cases, the real constructors are protected or private, neither of which can be accessed from outside.

For example, a short named constructor is this:

 class A
{
  public:
    static A createA() { return A(0); } // named constructor
  private:
    A (int x);
};
int main(void)
{
   A a = A::createA(); 
}

I thought static method can only access static data member, or access private data/method via an existing object. However, in the above code, private constructor A() isn't static, and at the time it is being called, no object exists either. So the only explanation I can think of is that static method can access non-static private method of the same class. Can anyone please either affirm or negate my thought, possibly with some lines of explanations?

I apologize if this is too trivial however the key words are too common and I wasn't able to find an answer in dozens of google pages. Thanks in advance.

Answer

NathanOliver picture NathanOliver · Aug 25, 2016

A static member function has the same access rights as a non static member function. So yes, it can access any public, protected, and private variable in the class. However you need to pass an instance of the class to the function for the function to be able to access the member. Otherwise a static function can only directly access any other static member in the class.