static members code example
Example 1: what is static method
A static method belongs to the class rather than the object.
There is no need to create the object to call the static methods.
A static method can access and change the value of the static variable
Example 2: static in class c++
#include
class Entity {
public:
static int x,y;
static void Print() {
std::cout << x << ", " << y << std::endl;
}// sta1tic methods can't access class non-static members
};
int Entity:: x;
int Entity:: y;// variable x and y are just in a name space and we declared them here
int main() {
Entity e;
Entity e1;
e.x = 5;
e.y = 6;
e1.x = 10;
e1.y = 10;
e.Print();//output => 10 because variable x and y being static point to same block of memory
e1.Print();//output => 10 because variable x and y being static point to same block of memory
Entity::x; //you can also acess static variables and functions like this without creating an instance
Entity::Print(); //you can also acess static variables and functions like this without creating an instance
std::cin.get();
}