How to create a static class in C++?

C++ProgrammingServer Side Programming

There is no such thing as a static class in C++. The closest approximation is a class that only contains static data members and static methods.

Static data members in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class. Static methods in a class can only access static data members, other static methods or any methods outside the class.

A program that demonstrates static data members and static methods in a class in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Example {
   public :
   static int a;
   static int func(int b) {
      cout << "Static member function called";
      cout << "\nThe value of b is: " << b;
   }
};
int Example::a=28;
int main() {
   Example obj;
   Example::func(8);
   cout << "\nThe value of the static data member a is: " << obj.a;
   return 0;
}

Output

The output of the above program is as follows.

Static member function called
The value of b is: 8
The value of the static data member a is: 28

Now let us understand the above program.

In the class Example, a is static data member of data type int. The method func() is a static method that prints "Static member function called" and displays the value of b. The code snippet that shows this is as follows.

class Example {
   public :
   static int a;
   static int func(int b) {
      cout << "Static member function called";
      cout << "\nThe value of b is: " << b;
   }
};
int Example::a = 28;

In the function main(), an object obj is created of class Example. The function func() is called by using the class name and scope resolution operator. Then the value of a is displayed. The code snippet that shows this is as follows.

int main() {
   Example obj;
   Example::func(8);
   cout << "\nThe value of the static data member a is: " << obj.a;
   return 0;
}
raja
Updated on 26-Jun-2020 14:17:37

Advertisements