Static Members in C++

When we declare a member of a class as static it means irrespective how many objects of the class are created, there is only one copy of the static member.We can define class members static using static keyword. 
By declaring a function member as static, you make it independent of any particular object of the class. We can call a static member function even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.
A static member function can only access static data member, other static member functions and any other functions from outside the class.
Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.
#include <iostream>

using namespace std;

class Demo
{
    private:
//static data members
        static int X;
        static int Y;
    Demo(){
        X=X+1;
        Y=Y+1;
            }

    public:
    //static member function
    static void  Print()
    {
        cout <<"Value of X: " << X << endl;
        cout <<"Value of Y: " << Y << endl;
        }
};

//static data members initializations
int Demo :: X =10;
int Demo :: Y =20;


int main()
{  
    //accessing print with class name
    cout<<"Printing without object :"<<endl;
    Demo::Print();
    
    Demo OB1;
    //accessing print with object name
    cout<<"Printing through object :"<<endl;
    OB1.Print();

    return 0;
}

That's all for now !!

No comments:

Post a Comment

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...