CPP Program to Implement Static Member Function in Class

Aim:

To implement static member function in class.

Algorithm:

  1. Create a class test with static data member as count.
  2. Create a member function to increment the count.
  3. Declare the static data member using the scope resolution operator.
  4. Display the count value.

Program:

#include <iostream>
using namespace std;
class MyClass{
private:
static int a;
public:
MyClass()
{
a++; 
}
static int print()
{
return a;
}
};
int MyClass::a = 0; 
int main() {
MyClass A,B,C,D; 
cout << "Number of objects: " << MyClass::print();
}

Execution:

Number of objects: 4

Result:

Thus, the Implementation static member function in class was executed successfully.

Leave a Comment