Member Avatar for danibecse

What is the purpose of static member functions in a class?

Static functions are generally used when you have static data members in a class and you want to be able to acess the static data. You have to have a satic function to acess static data since it is seperate from the objects of that class.

When you have a member variable which value you want to share among all instances of a class, you declare it as static. In order to access that member with a method, the method also has to be declared static.

#include <iostream>

class MyClass
{
   static int x;

public:
   static void IncX() 
   { 
        x++;
   }

   void Print()
   {
       std::cout  << x << std::endl;
   }

};

int MyClass::x = 10;

void main()
{
    MyClass a;
    MyClass b;

    // a.IncX() will generate an error
    MyClass::IncX(); 

    // value of x will now be 11 for both a and b
    a.Print();
    b.Print();

}
commented: Any other use it has......? +0

Also, if a there is a static member you could see the total number of instances of that class from your entire program.

#include <iostream>
using namespace std;
class StaticClass{
    static int count;
public:
    StaticClass(){
        count++;
    }

    static void printCount(){
        cout<<"Number of instances: "<<count<<endl;
    }
};

int StaticClass::count=0;
int main(){
    for (int i=0;i<10;i++){
        StaticClass* a = new StaticClass();
        delete a;
    }
    StaticClass::printCount();
    return (0);
}

Notice that here all the elements were deallocated, but still, the static member's value is 10. Basically, the static members are unique per class, and each instance of that class can use them, and the changes are visible to all the instances from that class.

Member Avatar for danibecse

Is the use of Static member function will reduce the usage of memory (as it does not creates any obeject)????????

Sorry Friends Unfortunately I deleted the danibecse membership
continue with this new one

Is the use of Static member function will reduce the usage of memory (as it does not creates any obeject)????????

What is the purpose of static member functions in a class?

Well, others have already pointed out one kind of purpose for static member functions. But there are many others too. In other words, there are many "tricks" that rely on a static member function(s). So, it's pretty hard to pinpoint a single purpose for them. Here is a list of the purposes that I can think of off the top of my head:

  • Access and manipulate some static data members (i.e., values globally associated to the class, not the individual instances, like instance counts, global parameters, etc.).
  • Write factory functions (or "named constructors") that allow you to create objects of the given class through a static member function (which has access to (private) constructors). This can be useful for many reasons, like:

    • Allocating the new objects through some alternate scheme (e.g., like a memory pool).
    • Enforcing the use of a smart-pointer to the objects (e.g., std::unique_ptr or std::shared_ptr) by making it impossible to create objects outside of the static "factory" functions.
    • Registering some information about created objects in some global repository / database (e.g., a garbage collection scheme, or just general system-wide lookups of objects in existence).
    • Enforcing a "single instance" rule in what is called a Singleton pattern.
    • Simply providing many alternative construction methods which have distinct names, promoting clarity as to what this particular construction method does (i.e., instead of relying on overloading of the constructors, which can be ambiguous and unclear as to what constructor does what). A typical example of that is constructing a 2D vector from either the x-y components or from the polar coordinates (r, theta), you couldn't do that with overloaded constructors, and it wouldn't be clear, but if you provide two static member function, like Vector2D::CreateFromXY(double,double) and Vector2D::CreateFromPolar(double,double), then it is really clear, and clarity is important. This is the so-called "Named Constructor" pattern.
    • Doing some post-construction initialization code. Once in a while, you find situations in which some of the initialization code of the object cannot be done in the constructor (requires the construction to be over). In this case, it is not convenient to require the user to always call a particular "init()" function after each construction of an object, so, by forcing to construction to go through a static member function, you can call that init() function without the user of your class ever knowing about it (i.e., that's the point of encapsulation).
    • .... etc.
  • Another purpose of static member functions is simply to define helper functions that are specific to the given class, but don't really require working directly with an object (instance). Helper functions might just be useful for the class and/or its derived classes, if so, better make it a (protected) static member function.
  • There are also many special purposes, like obtaining custom information about the type (e.g., in a type-identification system, or a globally-unique identifier (UUID)).
  • Finally, on a more advanced level, static member functions can be very useful in many types of generic programming and template meta-programming techniques. Because, in those realms, functions and classes are most often "parametrized by types" (templated) and static member functions are a good way to pass along associated function(s) (and information) related to those types (or template arguments).

Is the use of Static member function will reduce the usage of memory (as it does not creates any obeject)????????

I guess you could say that. But, remember, non-static member functions do not create objects either, they simply operate on an object (found through the "hidden" "this" pointer). Of course, that implies that you need to create the object first, before using a member function, which is, of course, not the case for a static member function. But this is mostly a matter of if the function has to operate on an object or not. If it has to, then an object has to exist (whether passed implicitely as the "this" pointer, or if passed as a parameter to a static member function or a free-function), so, there is no way out of it. If the function doesn't need to operate on an object, then making it a non-static member function is wasteful, and it doesn't make any sense from a semantics point of view (the meaning of the function), and thus, it should either be a static member function or a free function (if not specifically related to a class in particular). So, the argument about reducing memory usage is really not a central issue anywhere in this, the issue is mostly about semantics (i.e., having code that makes logical sense, and enforces certain rules).

You know you can write a simple program to find that out. You could also look at the link umesh314 posted and you should be able to figure it out. You can even do what I did and go to Google. Looks like the first link explains it pretty well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.