Why static methods cant access non static members?

A static variable will be available for the entire lifetime of the program, even before the object of call is being created.  See below code

class CreditCard
{
public:
    static int noOfCards;
    …
};
int CreditCard::noOfCards = 99;
int _tmain(int argc, _TCHAR* argv[])
{
   Console::WriteLine("{0}", CreditCard::noOfCards); 
   // This line will print 99.
   ...
}

Same holds true for the static functions declared in a class, with the limitation that A static member function can only access static class members.  We will see why cant static member function cant access not static member data.

In the following code:

class CreditCard
{
public:
   static int GetnoOfCards()
   {
       return noOfCards;
   }
   ...
private:
   static int noOfCards;
};
int CreditCard::noOfCards = 99;
int _tmain(int argc, _TCHAR* argv[])
{
   Console::WriteLine("{0}", CreditCard::GetnoOfCards());
   // This line will print 99
   ...

}

Its clear that we can access the static member function without creating the object of a class. But for non static members object must be declared or constructor must get called to assign them memory, they needs to be initialized  before they get used. Hence static methods cannot access the non static members.

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...