Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Static Member Function in C++ : With Code Examples

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

A static member function in C++ is a special type of member function of a class, which is not dependent upon any object of the class. C++ programmers use a combination of coding techniques including static member functions that maximise the efficiency of the code and improve its clarity. Static member functions for instance can be defined as functions embedded in a given class that classifies themselves as dependent on the class itself rather than normal members unique to each instance of that class. As they offer various benefits and features with this distinction, static member functions are a vital tool for C++ programmers.

 

In this article, we will discuss static member functions and why they are of utmost importance in C++ programming, features, code samples, properties and limitations of static member functions, examples of static member functions, and more. No matter if you are a novice in C++ or an expert with lots of coding experience, this static member function concept will certainly broaden your horizons.

What are Static Members in C++?

Static members or data members that are declared inside of a class using the static keyword are referred to as static members. Since these members are shared by all instances of the class, the class as a whole, not any specific object, is the owner of them. There are two types of static members in C++:

 

  • Static Data Members: Variables that keep a single shared copy across all instances of a class are known as static data members. This shared data is accessible to all class objects and is initialised just once.
  • Static Member Functions: These functions can only interact with other static member functions or static data members. They are unable to use the class’s functions or members with non-static data.

 

Syntax:

static int var_name; // declaring a static member function

 

Example:

#include <iostream> using namespace std; // Declare a class class LearnRate { public: static int rate; // Static data member declaration LearnRate() { rate++; } }; // Definition and initialisation of static data member int LearnRate::rate = 0; // Main Drive function int main() { LearnRate r1, r2, r3, r4; cout << "Number of objects created: " << LearnRate::rate << endl; return 0; }

Output:

Number of objects created: 4

In the above example, the rate is a static data member that keeps track of the number of objects created for the LearnRate class in C++.

What is Static Member Function?

A static member function is a function that belongs to the class rather than any individual object of the class. It can be invoked with the class name rather than an object and is defined with the static keyword. A static member function doesn’t depend on any class objects. It is possible to call a static member function in the absence of any class instances.

 

Points to note:

 

  • There cannot be static and nonstatic member functions with the same names and the same number and type of arguments in a C++ program.
  • Like static data members, you may access a static member function func_name() of a class ClassName without using an object of class ClassName.
  • A static member function cannot be declared using virtual, const, volatile, or const volatile keywords.
  • There is no ‘this’ pointer in the static member function in C++.
  • A static function can access only the names of static data members, enumerators, and nested types of the class in which it is declared.

 

Syntax:

class ClassName { public: static void staticFunctionName() { // Function body } };

Here,

  • The class keyword is used to define a class with the name ClassName.
  • A public access modifier indicates that the contents can be accessed from anywhere in the program.
  • The static keyword is used for the function name, which demonstrates the function’s static nature.

 

Example:

#include <iostream> using namespace std; // Declare a class class MyClass { public: // Static member function to calculate the area of a rectangle static int findArea(int x, int y) { return x * y; } }; int main() { // Calling the static member function using the class name int ans = MyClass::findArea(4, 5); cout << "The area of a rectangle with values 4 and 5 is: " << ans << endl; return 0; }

Output:

The area of a rectangle with values 4 and 5 is: 20

 

Explanation:

 

  • A findArea(int x, int y), static member function is declared of the MyClass class.
  • The function is called using the class name MyClass::findArea(4, 5); because static member functions do not require an instance of the class.
  • Finally, the function calculates and returns the area of the given integer values 4 and 5.

How to Declare and Define Static Member Functions

Declaration

 

Static member functions are declared using the static keyword in the class definition. They are declared inside the class, just like regular member functions, but with the static keyword preceding the function’s return type.

 

Syntax:

class ClassName { public: static ReturnType FunctionName(Parameters); };

Definition

The definition of a static member function is done outside the class, using the scope resolution operator (::).

 

Syntax:

ReturnType ClassName::FunctionName(Parameters) { // Function body }

How to Call Static Member Functions

There are two primary methods in C++ for calling static member functions:

 

Using the Scope Resolution operator (::): Since static member functions are part of the class and not associated with any particular instance, this is the most popular calling method.

 

Syntax:

ClassName::StaticFunctionName(Arguments);

 

Here,

  • ClassName: The name of the class that contains the static member function.
  • StaticFunctionName: The name of the static member function to be called.
  • Arguments: The actual values to be passed to the function (if any).

 

Example:

#include <iostream> using namespace std;   // Class Declaration class MyClass { public: // Static member function to find the area of a rectangle static int recArea(int x, int y) { return x * y; }   // Static member function to find the area of square static int squareArea(int a) { return a * a; } };   int main() { // Calling static member functions using the MyClass class name and scope resolution operator int rcArea = MyClass::recArea(3, 34); int sqArea = MyClass::squareArea(35);   // Displaying the results cout << "Area of Rectangle: " << rcArea << endl; cout << "Area of Square: " << sqArea << endl;   return 0; }

Output:

Area of Rectangle: 102 Area of Square: 1225

Explanation:

 

  • The class MyClass has two static member functions: recArea and squareArea. They find the area of a rectangle and square using the parameters.
  • In the main function, we call these static member functions using the class name MyClass followed by the scope resolution operator (::) and the function name.
  • Here, we didn’t create any object of the Calculator class as the static member functions can be accessed directly through the class name.

 

  1. Using Class Object: Static member functions can also be called using an object of the class, however, this is less common and is usually not recommended.

 

Syntax:

ObjectName.StaticFunctionName(Arguments);

 

Here,

  • ObjectName: An instance (object) of the class that contains the static member function.
  • StaticFunctionName: The name of the static member function to be called.
  • Arguments: The actual values to be passed to the function (if any).

 

Example:

#include <iostream> using namespace std;   // Class Declaration class MyClass { public: // Static member function to find the area of a rectangle static int recArea(int x, int y) { return x * y; }   // Static member function to find the area of square static int squareArea(int a) { return a * a; }   // Non-static member function to display a message void display() { cout << "MyClass class object" << endl; } };   int main() { // Creating an object of the class MyClass obj;   // Calling static member function using the object to find the area of a rectangle int rArea = obj.recArea(14, 16);   // Calling static member function using the object to find the area of the square int sArea = obj.squareArea(45);   // Displaying the result cout << "Area of rectangle: " << rArea << endl; cout << "Area of square: " << sArea << endl;   // Calling non-static member function using the object obj.display();   return 0; }

Output:

Area of rectangle: 224 Area of square: 2025 MyClass class object

Explanation:

 

  • The MyClass class has a static member function recArea that calculates the area of a rectangle given its width (x) and height (y), and a function squareArea() that calculates the area of the square using `a`.
  • In the main function, we create an object `obj` of the MyClass class and use this object to call the static member functions squareArea() and recArea(). Even though this syntax is valid, it’s not ideal.
  • Using the object obj to call a static member function can give the false impression that the function squareArea() and recArea() are tied to the object `obj`, which is not the case. The function is still a class-level function.
  • The object `obj` is used to call the non-static member function display, which is appropriate as non-static functions are tied to objects.
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Properties of Static Member Function

There are various properties of static member functions in C++, that help them differentiate from other member functions. Here are a few of them:

 

  • Class Level Association: Static member functions belong to the class and not to any object. Therefore they can be called without creating an object of that particular class.
  • Scope: Static functions are restricted to the file scope, meaning that they can only be seen within the file they were defined in. There is no way to reach them from outside the file unless the class is extended.
  • No `this` Pointer: Since static member functions don’t belong to any object, they cannot have the `this` pointer. That is why they are not able to work with any non-static data members or functions.
  • Access to Static Members: Static member functions may only use the static data members and other member functions of the same class that are static. They cannot access non-static members.
  • Visibility: Static member functions’ visibility, be it public, private, or protected, is governed by the access specifier applied to the static member function’s class. They are subjected to the same visibility guidelines as any other member functions.
  • Utility functions: Static function in C++ is mostly used for building such kinds of methods which are utility methods but do not have to change or use any state of the object.
  • Overloading and inheritance: Static member functions can be treated as normal member functions and overloaded. However, they can’t be virtual, as they do not support runtime polymorphism.

Why are Static Member Functions Required?

Many functions need to be defined as static member functions in C++ when the function needs to work at a class level or provide some services that are not related to the object. Some of the most common purposes of using static member functions are:

 

  • Utility Functions: There are operations related to the class that can be implemented using static member functions as utility functions without the interpolation of any data related to an instance of the class. For example, in class methods, the function whose responsibility is to check input data relevant to the class can be indicated.
  • Global-like Functionality: They offer a means of encapsulating related functionality and implementing global-like functionality inside the class’s boundaries.
  • Accessing Static Data Members: There are cases whereby you have static data members in your class, in such scenarios, it is customary to have static member functions for accessing data members because the non-static member functions are unable to access the static members directly.
  • Code Organisation: Clustering together related functions, which are most likely to use a static member function of a class in C++ will reduce the destruction of code structure. In that way, it is obvious which functions are for which class enhances the order of your code.
  • Encapsulation: Using static member functions helps in hiding the implementation related to class level but does not pertain to objects specific to one code. This helps to avoid unnecessary code duplication and confusion.
  • Factory Methods: Static data member functions are typically used to implement methods called factory methods that construct and return the objects of the class.

Difference Between Regular Member and Static Member Functions in C++

 

Criteria Regular Member Function Static Member Function
Association They belong to a specific object of the class in C++. They belong to the class itself, not to any particular object.
Access to Class Members Regular member functions can access both static and non-static members of the class. They can only access static members of the class.
`this` pointer Regular member functions have access to the implicit `this` pointer, referring to the calling object. They do not have access to `this` pointer.
Calling Convention They are called through an object or reference to an object (object.function()). They can be called using the class name (ClassName::function()).
Virtual Functions Regular member functions can be declared as virtual. They cannot be declared as virtual, as they are not associated with any object.
Overloading They can be overloaded based on parameter types or numbers. They can also be overloaded, but cannot be virtual.
Polymorphism They can have polymorphism. They cannot have polymorphism.
Invocation without Object Regular members cannot be invoked without an object of the class. They can be invoked without creating an object of the class.
Memory Allocation While object creation, the memory is allocated. Memory exits independently.
Use Cases Multiple use cases such as when the function needs to manipulate object-specific data. Used for utility functions that are class-specific and not object-specific.
Lifetime They are with objects for a lifetime. They are with the class for a lifetime.
Function Signature Requirement They can have any return type and parameters. They can have any return type and parameters but not the `this` pointer.

Use Cases of Static Member Functions

There are multiple use cases of static member functions in C++, and below are some of them, but are not limited to:

 

  1. Utility Functions: Functions relevant to the class that do not need objects, for example, various mathematical functions or data member validation.
  2. Factory Methods: This is a method that instantiates the class and returns a class object. These can be called without an object because they are static.
  3. Singleton Pattern: This is a design pattern in which a static member function is used to provide access to only one instance of the class, called singleton.
  4. Access To Static Data Members: Static member functions can also, in a limited manner, help here when there are static data members that need to be accessed or modified.
  5. Callbacks: C-style function APIs often use function pointers for which static member functions help because there is no implicit `this` pointer.

 

Example:

#include <iostream> using namespace std;  // Class Declaration class SingletonClass { private: static SingletonClass* instance; // Static data member SingletonClass() {} // Private constructor  public: static SingletonClass* showInstance() { if (instance == nullptr) { instance = new SingletonClass(); } return instance; } };  // Definition of static data member SingletonClass* SingletonClass::instance = nullptr;  int main() { SingletonClass* s1 = SingletonClass::showInstance(); SingletonClass* s2 = SingletonClass::showInstance();  if (s1 != s2) { cout << "Instances S1 and S2 are different." << endl; } else { cout << "S1 and S2 instances are the same." << endl; }  return 0; }

Output:

Both instances are the same.

Explanation:

 

In this example, the showInstance() function is a static member function used to ensure that only one instance of the SingletonClass class is created.

Limitations of Static Member Function

Understand the limitations of static member functions in C++ while considering this function to be included in your next C++ program code:

 

  • No Access to Non-Static Members: Static member functions are unable to contain or make reference to any non-static data members or member functions, and thus limit their capabilities.
  • No `this` Pointer: Since they are not associated with any object, static member functions do not have a `this` pointer.
  • Perception of Static Functions: Static member functions are primarily made in order to perform class-wide operations and utility functions. Non-static members in any way cannot be reached and their state cannot be modified.
  • Not Polymorphic: Static member functions cannot be virtual and therefore any inheritance usage or polymorphism is a constraint.
  • Restriction of Appropriate Use: Static member functions use is vital but the record should be very low to only a few design patterns since chances are some designs will need too many of them.
  • Initialisation and Lifetime: The static data members inside these static member functions are only initialised once and only when the program executes, usually at declaration. This may not be appropriate for some situations where objects will need to be initialised or de-allocated while the program is still running.

Best Practices for Using Static Member Functions

Some of the best practices one must follow while working with static member functions in C++ are as follows:

 

  • Use Only When Appropriate: Only use static member functions when the logic behind them is unaffected by object-specific data.
  • Encapsulate Class-Level Logic: To encapsulate logic linked to the class but not to any specific instance, use static member functions.
  • Avoid Overuse: Using static member functions excessively can result in hard-to-manage and maintain code, therefore, always use them sparingly.
  • Factory Methods and Singleton: Use static member functions for factory methods and the Singleton pattern, where creating instances needs to be controlled.

Common Mistakes to Avoid with Static Member Functions

Users often forget to apply the best practices while working with static member functions in C++, and make mistakes that they must avoid:

 

  • Accessing Non-Static Members: Attempting to dynamically access static member functions, non-static members, leads to a compilation error.
  • Overuse: Using static member functions for logic that should be encapsulated within objects, leading to poor object-oriented design.
  • Incorrect Invocation: An object is used to call a static member function, making a lot of people not understand such usages.

 

Also Read: C++ Interview Questions and Answers

Conclusion

C++ static member functions are a useful feature that helps in configuring class functionalities that are independent of class instances. Particularly, they are helpful for utility functions, the use of static data members, singleton implementation, and factory method patterns. Some of them include benefits such as encapsulation and utility, whereas some are expressed as limitations such as no access to non-static members and no polymorphism.

 

Understanding the properties, benefits, and limitations of static member functions can help you utilise them effectively in your C++ programs, improving code organisation and readability. By accessing their positive side while being sure to keep in mind their negative implications, C++ programmers will be able to set specific programming problems with more elegant and better-quality solutions. This is a great feature to make C++ programs more elegant and robust when used appropriately, and with the correct applications and discipline of best practices, static member functions will be a part of the C++ toolkit you couldn’t have imagined.

FAQs
A function that is defined outside of any class but designated as static inside a particular file or translation unit is known as a static free function in C++. This indicates that the function has an internal connection, which prevents it from being accessed or linked from other files within the same program and limits its visibility to the file in which it is defined.
No, static member functions cannot access non-static data members or functions directly, as they do not have a `this` pointer.
No, it is not possible to declare static member functions as virtual class functions in C++. Polymorphism and dynamic dispatch, which rely on the runtime type of static objects, are linked to the idea of virtual functions. Static member functions, however, are not dependent on the state of any object and do not work on particular object instances. They do not engage in polymorphism as a result, therefore calling them virtual is meaningless.
Below is the difference between static and non-static member functions: Static Member Functions:
  • Belong to the class itself, not to any specific object.
  • Can only access static members (variables and functions) of the class.
  • Do not have access to the `this` pointer.
  • Can be called using the class name and the scope resolution operator (ClassName::FunctionName()).
  Non-Static Member Functions:
  • Belong to an instance of the class and are tied to a specific object.
  • Can access both static and non-static members of the class.
  • Have access to the `this` pointer, which refers to the calling object.
  • Must be called through an object or a reference to an object (object.FunctionName()).
 
It is allowed in C++, but it is not recommended because it can be misleading. It suggests that the static function is tied to the object, which is not the case. Static functions should be called using the class name to emphasise that they are part of the class, not any specific object.   Example: class Car { public: static void display() { std::cout << "Static function called!" << std::endl; } }; int main() { Car car; car.display();  // Valid but not recommended. Car::display();  // Recommended way to call a static member function. return 0; }

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

19 October, 12:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved