Defining static members in C++


Static members in a class in C++ can be defined using the static keyword. There is only one copy of the static class member in memory, regardless of the number of objects of the class. So the static member is shared by all the class objects.

The static class member is initialized to zero when the first object of the class is created if it is not initialized in any other way.

A program that demonstrates the definition of the static class members is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;

class Point{
   int x;
   int y;

   public:
   static int count;

   Point(int x1, int y1){
      x = x1;
      y = y1;

      count++;
   }

   void display(){
      cout<<"The point is ("<<x<<","<<y<<")\n";
   }
};

int Point::count = 0;

int main(void){
   Point p1(10,5);
   Point p2(7,9);
   Point p3(1,2);

   p1.display();
   p2.display();
   p3.display();

   cout<<"\nThe number of objects are: "<<Point::count;

   return 0;
}

The output of the above program is as follows −

The point is (10,5)
The point is (7,9)
The point is (1,2)

The number of objects are: 3

Now let us understand the above program.

The class Point has 2 data members x and y that constitute a point. There is also a static member count that monitors the numbers of objects created of class Point. The constructor Point() initializes the values of x and y and the function display() displays their values. The code snippet that shows this is as follows −

class Point{
   int x;
   int y;

   public:
   static int count;

   Point(int x1, int y1){
      x = x1;
      y = y1;

      count++;
   }

   void display(){
      cout<<"The point is ("<<x<<","<<y<<")\n";
   }
};

In the function main(), there are 3 objects created of class Point. Then the values of these objects are displayed by calling the function display(). Then the value of count is displayed. The code snippet that shows this is as follows −

Point p1(10,5);
Point p2(7,9);
Point p3(1,2);

p1.display();
p2.display();
p3.display();

cout<<"\nThe number of objects are: "<<Point::count;

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements