Static Member Function Example in C++


In this program, a class Test is defined, which has a private member a and b and a public static variable count. The count variable is initialized to 0. A default constructor is defined for the Test class, which initializes the a and b member variables to 10 and increments the count variable by 1. A static member function getCount() is also defined, which returns the value of the count variable.

In the main() function, an object t1 of the Test class is created, which invokes the default constructor. The getCount() static member function is then called using the Test class name, and the value returned by the function is printed to the console using cout. Since only one object of the Test class is created, the value of the count variable is 1, and that is what is printed to the console.

Source Code

#include<iostream>
//Static Member Variable
using namespace std;

class Test
{

private :
    int a,b;
public:
    static int count;
    Test()
    {
        a=10;
        b=10;
        count++;
    }
    static int getCount()  //Static Member function returns only static variables
    {
        return count;
    }
};
int Test::count=0;
int main()
{
    Test t1;
    cout<<"T1 :"<<Test::getCount();
}

To download raw file Click Here

Output

T1 :1

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples