Why we need static member function in C++

Static member functions are used to maintain a single copy of a class member function across different objects of the class. Static member functions can be called either by itself, without instantiating any object, by using class name and scope resolution operator (::) or in connection with an object. - 

Restrictions on static member functions are : 

1. They can directly refer to other static members of the class. 

2. Static member functions do not have this pointer. 3. 

Static member function can not be virtual. 


#include <iostream>

using namespace std;

class A{

    static int b;

public:
    //Static function
    static int GetValue(){
        b = 10;
        return b;
    }
};

//initialize static variable
int A::b =50;

int main(){

    //Static functin call
    cout<< A::GetValue();

    return 0; 

}

In above program gives output 10, we have a static variable b of int type and have initialize to 50, but inside static function the value of static variable b has been modified to 10. Hence, program will work correctly.

 

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...