Home » C++ programming language

Static member function in C++

Learn: What are the static member functions, why the used and how can we access static data members through static member functions in C++ programming language?

In the last post, we have discussed about the static data member in C++ and we discussed that a static data member can accessed through the member functions, but the function should be static member function

A static member function is a special member function, which is used to access only static data members, any other normal data member cannot be accessed through static member function. Just like static data member, static member function is also a class function; it is not associated with any class object.

We can access a static member function with class name, by using following syntax:

	class_name:: function_name(perameter);

Consider the example:

#include <iostream>

using namespace std;

class Demo
		//static data members
		static int X;
		static int Y;

	//static member function
	static void  Print()
		cout <<"Value of X: " << X << endl;
		cout <<"Value of Y: " << Y << endl;

//static data members initializations
int Demo :: X =10;
int Demo :: Y =20;

int main()
	Demo OB;
	//accessing class name with object name
	cout<<"Printing through object name:"<<endl;
	//accessing class name with class name
	cout<<"Printing through class name:"<<endl;
	return 0;


Printing through object name:
Value of X: 10
Value of Y: 20
Printing through class name:
Value of X: 10
Value of Y: 20

In above program X and Y are two static data members and print() is a static member function. According to the rule of static in C++, only static member function can access static data members. Non-static data member can never be accessed through static member functions.

Note: Inline function can never be static.

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.