×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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

What is static member function in C++?

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.

Accessing static member function

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

class_name:: function_name(perameter);

Example of static member function

Here is an example of demonstrating the concept of static data members and accessing them:

#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

Explanation

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.