C++ Static Members and Functions
- Static member variable is intialized to zero when the object of its class is created. No other initalization is permitted.
- Only one copy of that member is created for entire class.
- It is shared by all the objects of that class.
- It is visible only within the class, but its life time is the entire program.
Member function of a class can also be declared as static. But the static member function can access only static data member.
Syntax:
static data_type variable_name;
Example:
#include<iostream> using namespace std; class Rectangle{ static int c;// static member data public: void get_data() { c++; } static int show_data() // static member function { return c; } }; int Rectangle::c;// initialized to zero int main(){ Rectangle r1; Rectangle r2; r1.get_data(); r2.get_data(); cout << "Final Stage Count: " << Rectangle::show_data() << endl; return 0; }
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.