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
{
	private:	
		//static data members
		static int X;
		static int Y;

	public:
	//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;
	OB.Print();
	
	//accessing class name with class name
	cout<<"Printing through class name:"<<endl;
	Demo::Print();
	
	return 0;
}

Output

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.


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.