When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.
Static Function is a you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator :: .
This program demonstrates the use of static variables and a static function in a C++ class. The class student has a private static integer variable x, which is initialized to 0. It also has two private non-static member variables, a string name and an integer age. The class has a constructor that takes two arguments, name and age, and initializes these member variables. The constructor also increments the static variable x by 1. The class has a member function print() that prints the name and age of the student.
The class also has a static member function getCount() that returns the value of the static variable x. This function does not have access to any non-static member variables or functions of the class, since it is a static member function.
In the main() function, three objects of the student class are created using the constructor. The print() function is called for each object to print their details. Finally, the static function getCount() is called using the class name to print the total number of students created.
#include<iostream> using namespace std; //Static variables and Static Function class student { private: static int x; string name; int age; public: student(string n,int a) { x++; name=n; age=a; } void print() { cout<<"Name : "<<name<<endl; cout<<"Age : "<<age<<endl; cout<<"\n"; } static int getCount() { return x; } }; //Static Variable int student::x=0; int main() { student s1("Ram",25); student s2("Sam",22); student s3("Kumar",12); s1.print(); s2.print(); s3.print(); cout<<"Total Students : "<<student::getCount()<<endl; return 0; }
Name : Ram Age : 25 Name : Sam Age : 22 Name : Kumar Age : 12 Total Students : 3To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions