Home >>C++ Tutorial >C++ Static
A keyword or modifier that is known to belong to the type and not instance is known as the static in C++. In order to access the static members, instance is not required and it can be class, properties, and operator.
There are many advantages of the static keyword in C++ but here is the main advantage of the same:
Any field in the C++ that is declared as static is known to be as static field. Whenever an object is created the only one copy of the static field is generally created in the memory which is totally different from an instance field that gets the memory allotted to them each time. Static field is shared to all of the objects. In order to refer the property that is common in all of the objects such as rate of interest in the case of the account, School name in case of the students and many more.
Here are the examples of the C++ static that will help you understand the topic from an application view:
#include <iostream> using namespace std; class Student{ public: int roll_no; string name; static float marks; Student(int roll, string name) { this->roll_no = roll; this->name = name; } void show() { cout<<"Name "<<name<<endl; cout<<"Roll No "<<roll_no<<endl; } }; float Student::marks=96.5; int main(void) { Student stu =Student(101, "Test"); stu.show(); cout <<"Marks="<<stu.marks; return 0; }
#include <iostream> using namespace std; class Student { public: static int i; Student() { }; }; int Student::i=1; int main() { Student stu; cout << stu.i; // prints value of i return 0; }