Você está na página 1de 2

The Static Keyword The static keyword is a modifier, that can be applied to the members of the clas s.i.e.

the data members and the member functions of the class but not to the clas s itself. Modifiers are a feature of the language to modify the behavior of the members in some way or the other. Thus static modifies the behavior of the membe rs on which it is applied. Static keyword can be applied toThe data members The member functions. Static Keyword to the data members: Static keyword when applied to the variables, makes them the class variables ins tead of the instance variables. Thus these variables are shared between objects. i.e. Each object refers to the same memory location. There is no copy of the var iable created. All the objects of the class can modify the static variable, but the changes mad e will be permanent and visible by all other objects. The memory for static variables is created when the class is loaded. Since these are class variables and not object variables, these are not allocated memory du ring object creation but before that during class loading. Static variables are mostly used for object counting. Here the instance variable cannot be used as it is created with the object and each object has its own ins tance variable. So the class variable is required. A simple example of object counting is given below:

class count { static int ctr; //static variable for object counting public: count() // constructor of the class { ctr++; } void display() { cout << "Total objects=" << ctr; } }; int count::ctr=0; void main() { count c1,c2,c3; c1.display(); getch(); }

Here the output is 3 as three objects are created. Static Keyword to the member functions:

The static keyword when applied to the member functions, binds them to the class rather than a particular function. That is they can be invoked by the name of t he class rather than the object. But they can be invoked even by the objects. An important point to be noted here is that non-static members cannot be used wi thin the static functions. These cannot access the instance variables or instanc e methods directly. Further they cannot use the 'this' keyword.i.e. they do not have the 'this' pointer and may not be virtual. A simple example showing the usage of the static method is given below:

class Test { int y; public: Test() { y=0; } static void demo() { cout << "This is a static function"; } void display() { cout << "The value of y is " << y; } }; void main() { Test.demo(); Test t1; t1.display(); }

Here we can see that the static function demo is invoked by the class name even before any object is created. But display is called by the object only. This is the use of 'static' in C++.

Você também pode gostar