Static Functions: Access Member Function Without Object in C++

A type of member function that can be accessed without any object of the class is called static function. Normally, a member function of any class cannot be accessed or executed without creating an object of that class. In some situations, a member function has to be executed without referencing any object. Here a static member function is useful because it is accessible without any object of class.

The static data members of a class are not created for each object. The class creates only one data member for all objects. Because static functions are not attached to a particular object, they can be called directly by using the class name and the scope resolution operator.

The static data member is defined when the program is executed. The program may require to access a static data member before creating an object. The static member functions is used to access a static data member.

There are two interesting facts about static functions:

  • They don’t have this pointer. The this pointer always points to the object that the member function is working on. Static functions don’t work on an object, so this pointer is not available.
  • Static functions can only access static member variables. They can’t access non-static member variables. This is because non-static member variables must belong to a class object, and static functions have no class object to work with.

C++ Code:

Program Logic:

The above program declares a class example with a static data member number. The following statement defines the data member with an initial value of 10:

The static data member exists in the memory even before creating an object. The program also declares a static member function show() that displays the value of number. The program calls the static member function without creating an object of the class as follows:

You can see we used static function show() before without creating any object of class.

Program Output:

Using Static functions in C++

If you have any question then you can ask me in comments. I would like to answer them.

if you liked this article, then please consider sharing it with your friends.

You can also Click Here To Download Exercise Files.