Static Member Function in C++ (Examples)
What is a Static Function in C++?
In C++ classes, a static member is a class member that belongs to the class rather than to its objects. You will only have one copy of the membership. This is the case irrespective of the number of objects you create.
When a class function is defined as static, all class objects share a static class member. The static function can therefore be accessed without creating any class objects and becomes independent of class objects. A static data member in C++ can access other static functions, outside the class only.
Why use Static Functions?
Unlike C++ global functions, static functions are only accessible from the file of declaration. If there is a need to restrict access to a function, make it static.
Use a static function to restrict the reuse of the same function name in another file.
Defining Static Functions in C++
Syntax:
static int myfunc(void) { cout("Example of C++ static function "); }
In the above example, we are defining a static function named myfunc. Notice the use of the static keyword in the definition. The keyword comes before the function name.
Static Member Function in C++
When a function member is declared static, it becomes independent of other objects in the class. You can call a static member function even if no other class objects exist.
To access class names, you should use the name of the class and the scope resolution operator (::)
. A static function can only access other static functions, static data members, and other functions outside the class. The scope of static member functions lies within the class, and they cannot access this class pointer.
Example 1
#include<iostream> using namespace std; class BoxClass { public: static int count; BoxClass(double l = 2.0, double b = 2.0, double h = 2.0) { cout << "Class constructor called." << endl; length = l; breadth = b; height = h; count++; } double getVolume() { return length * breadth * height; } static int getCount() { return count; } private: double length; double breadth; double height; }; int BoxClass::count = 0; int main(void) { cout << "Inital value of count is : " << BoxClass::getCount() << endl; BoxClass Box1(3.2, 1.4, 1.8); BoxClass Box2(7.5, 4.0, 4.0); cout << "Final value of count is : " << BoxClass::getCount() << endl; return 0; }
Output:
Here is a screenshot of the code:
Code Explanation:
- Including the iostream header file in our C++ program to use its functions.
- Include the std namespace in the code to use its classes without calling it.
- Create a class named BoxClass.
- Use the public access modifier to mark a class member which is publicly accessible.
- The declare a static class member named count.
- Use a class contructor to initialize three variables of a double type.
- Print some text on the console. The endl (end line) function moves the mouse cursor into the next line.
- Initialize the value of l to variable length.
- Initialize the value of b to variable breadth.
- Initialize the value of h to variable height.
- Then Increase the value of the variable count by 1 each time a new object is created.
- End of the constructor body.
- Create a function named doublevolume().
- Define what the doubleVolume() function will return. It should return the multiplication of length, breadth, and height variables.
- End of the doubleVolume() function body.
- Declare a static function named getCount().
- The getCount() function should return the value of the count variable.
- End of the body of the getCount() function.
- Use the private access modifier to mark a class member as publicly accessible.
- Declaring a class member named length of a double data type. It will be privately accessible.
- Declare another class member named breadth of a double data type. It will be privately accessible.
- Declaring a class member named height of double data type. It will be privately accessible.
- End of the body of the BoxClass class.
- Then Initialize a static member of the BoxClass class.
- Calling the main() function. The C++ program logic should be added within the body of that function.
- Print some text on the console stating the current number of objects before new objects are created.
- Declare an object named Box1, which is one of the instance of the class BoxClass. The breadth, length, and height values should be specified within the parenthesis.
- Declare an object named Box2, which is an instance of the class BoxClass. The breadth, length, and height values have been specified within the parenthesis.
- Print some text on the console stating the current number of objects after the creation of new objects.
- The C++ program must return value upon successful completion.
- End of the body of function main().
Accessing Static Functions
You don’t need to create a class object to access a static function. Instead, you can use the class name and scope resolution operator (::)
.
Syntax:
className::funcName
Above, the className is the name of the class where the static function has been defined. The funcName is the name assigned to the static function.
Example 2
#include<iostream> using namespace std; class MyClass { public: static void msgFunc() { cout << "Welcome to Guru99!"; } }; int main() { MyClass::msgFunc(); }
Output:
Here is a screenshot of the code:
Code Explanation:
- Including the iostream header file in our program to use its functions.
- Include the std namespace in your code to use its classes without calling it.
- Create a class named MyClass.
- Use the public access modifier to mark a class member as publicly accessible.
- Declaring a static function named msgFunc(). The static keyword makes the function static.
- Specify the text to print on the console once the above function is called/invoked.
- End of the body of the msgFunc() function.
- End the class body.
- Calling the main() function.
- Call the static function named msgFunc().
- End of the body of function main().
Accessing Static Variables
Static variables belong to a class rather than to class objects. If a static variable is public, it’s accessible using the class name and using the scope resolution operator. However, this is not possible if a static member is private.
Normally, private variables are accessed using public functions. However, a class instance/object must be created. The solution is to use a static function.
Example 3: Static variable in C++ class
#include<iostream> using namespace std; class AClass { private: static int myvar; public: static int getVar() { return myvar; } }; int AClass::myvar = 23; int main() { cout <<"The value of myvar is: "<< AClass::getVar() << '\n'; }
Output:
Here is a screenshot of the code:
Code Explanation:
- Including the iostream header file in our program.
- Include the std namespace in this program to use its classes without calling.
- Create a class named AClass.
- Use the private access modifier to make the variable myvar privately accessible.
- Create a static integer variable named myvar.
- Use the public access modifier which mark the function getVar() as publicly accessible.
- Creating a static function named getVar().
- The getVar() function should able to return the value of variable myvar.
- End of the body of the function getVar().
- End of the body of the class AClass.
- Assign the variable myvar a value of 23. We have used the class name and scope resolution operator for this.
- Calling the main() function.
- Print the value of variable myVar on the console alongside other text. We have used the class name, the static function, and the scope resolution operator to access this variable’s value.
- The end of the main() function body.
this Pointer in Static Functions
A static function is not attached to an object. That is why static functions don’t have this pointer. An object’s pointer usually points to the object it is currently working on. Since static functions do not work with objects, there is no need for this pointer.
Static functions have direct access to other static members. However, this isn’t the case with no-static members. The reason is that non-static members have to belong to an object, but static functions don’t have objects to work with.
Example 4
It’s possible to define a static function outside class declaration. Let us demonstrate this:
#include<iostream> using namespace std; class NumGenerator { private: static int nextNum; public: static int getNextNum(); }; int NumGenerator::nextNum = 1; int NumGenerator::getNextNum() { return nextNum++; } int main() { for (int count = 0; count < 5; ++count) std::cout << "The next number is: " << NumGenerator::getNextNum() << '\n'; return 0; }
Output:
Here is a screenshot of your code:
Code Explanation:
- Including the iostream header file in our code to use its functions.
- Include the std namespace in our code to use its classes without calling it.
- Create a class named NumGenerator.
- Using the private access modifier to mark the variable, we are about to create as privately accessible.
- Create a static integer variable named nextNum.
- Using the public access modifier that helps you to mark the variable we are about to create as publicly accessible.
- Declaring a static function named getNextNum().
- End of the class body.
- Assign the variable nextNum a value of 1. We have done this using the class name, the variable name, and scope resolution operator.
- Defining the getNextNum() static function outside the class.
- Specify the action to be taken when the above function is called/invoked. It will increment the value of variable nextNum by 1.
- End of definition of the function getNextNum().
- Calling the main() function. The C++ program logic should be added within the body of this function.
- Use a for loop to create a variable named count. The value of this variable should increment from 0 to 4. After every iteration, the variable’s value will increase by 1.
- Printing the value of variable nextNum alongside other text on the console at each iteration. The value is accessed using the getNextNum() function.
- This C++ program must return value upon successful completion.
- End of the main() function.
Summary
- C++ static members are class members that belong to the class rather than its objects.
- You will only have one copy of a static member regardless of the number of objects you create.
- All class objects share each static class member.
- After defining a class function as static, it becomes independent of the class objects.
- A static function can be accessed even if you don’t create any class object.
- However, static functions don’t have this object, which points to class objects.