Jump to content

  • Log In with Google      Sign In   
  • Create Account


#Actualkuramayoko10

Posted 07 October 2012 - 01:12 PM

A static method has access to all parts of the class. What it doesn't have is a `this' pointer, but if it handles any instances of the class, it has full access to those instances, not only through the public interface. Think of the `dot' example that Lauris posted above.


Ah, I was just talking about basic (non-static) variables declared in the class.
Like in the following example:

#include <cstdio>
#include <cstdlib>
class MyClass
{
private:
	  int var1;
	  static int var2;
public:
	  MyClass()
	  {
		  var1 = 1;
	  }

	  static void printVar()
	  {
		  printf("var1: %d\n", var1);
		  printf("var2: %d\n", var2);
	  }
};

int MyClass::var2 = 2;

int main(int argc, char *argv[])
{
	MyClass::printVar();

	return 0;
}
The first printf() inside the printVar static method refers to a non-static variable declared in the class.
As result it yields the following error:
error: invalid use of member 'MyClass::var1' in static member function

If you comment that line, it will work fine with the static variable var2.

Just fixing my previous comment...

#1kuramayoko10

Posted 07 October 2012 - 01:12 PM

A static method has access to all parts of the class. What it doesn't have is a `this' pointer, but if it handles any instances of the class, it has full access to those instances, not only through the public interface. Think of the `dot' example that Lauris posted above.


Ah, I was just talking about basic (non-static) variables declared in the class.
Like in the following example:

#include <cstdio>
#include <cstdlib>
class MyClass
{
private:
	  int var1;
	  static int var2;
public:
	  MyClass()
	  {
		  var1 = 1;
	  }

	  static void printVar()
	  {
		  printf("var1: %d\n", var1);
		  printf("var2: %d\n", var2);
	  }
};

int MyClass::var2 = 2;

int main(int argc, char *argv[])
{
	MyClass::printVar();

	return 0;
}
The first printf() inside the printVar static method refers to a non-static variable declared in the class.
As result it yields the following error:
error: invalid use of member 'MyClass::var1' in static member function

If you comment that line it will work fine with the static variable.

Just fixing my previous comment...

PARTNERS