C++ Static Data Members

What are static data members

If a data member of a class is declared as static then only one copy of that data members is created for entire class and all objects of that class can share that data.

Syntax :-

datatype className :: staticMemberName = value

Example :-

#include <iostream>
using namespace std;
class Circle {
    int r;
    static float pi;
    Circle(int n)
      r = n;

    void area()
      cout <<"Area of circle is "<< pi * r *r <<endl;

float Circle :: pi = 3.14;
int main() {

Circle a(2);

return 0;

Output :-

Area of circle is 12.56

In this program we declared a variable pi as static . And we initialised its value which is then used by all the objects of a class. Its simply if in a program you want one value to be shared by any object of a class you can use static data members feature of C++.