Home >>C++ Tutorial >C++ Static

C++ Static

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.

Advantage of C++ static keyword

There are many advantages of the static keyword in C++ but here is the main advantage of the same:

  • Memory efficient : As a matter of fact we already know that the instance in not required to access the static members hence, the memory is saved and the on the top of that it generally belongs to the type hence, the memory will not get allocated each time an instance is created.

C++ Static Field

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;  
}      
Output : Name Test
Roll No 101
Marks=96.5

Example 2

#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;
}
Output : 1

No Sidebar ads