Question:
Why do we need static members in a class in C++ or any OOP language?
Maxood
2010-05-15 04:43:38 UTC
Why and when do we need static members in a class in C++ or any OOP language? Provide scenarios and examples.
Seven answers:
ʃοχειλ
2010-05-17 13:41:26 UTC
static keyword has three uses in C++ language. You have just asked about one of them:



1) a static may be used as a modifier of a local variable like:



int some_function ()

{

static int n = 1;



return n++;

}



Unlike normal local variables, static local variable would remain alive and keep its recent value as long as program runs. it means that the variable n above would have different values in each call of the function some_function (). For the first call, it returns 1 and will be updated to 2. For the second call, it will return 2 and be updated to 3,...



2) static may be used as a modifier to a global variable or function (none-class member function or variable).



Suppose we have a project in some C/C++ programming environment, and we have the following variable and function definitions in one of the source files (source1.cpp):





// source1.cpp

static int xs = 0;

static void fs ()

{

//...

}



int xn = 0;

void fn ()

{

//...

}



Now, let's ask a question: We are writing the code for another file (source2.cpp). Can we accesses these variables and functions (xs, fs(), xn, fn() which are defined in source1.cpp) in our other source files (source2.cpp)?



The answer is YES for xn and fn() and NO for xs and fs(), because xs and fs () are static. We cannot access the static global variables of other source files, but we could access the non-static variables and functions by declaring them as external:



extern int xn; // OK

extern void fn (); // OK



Sure, compiler would generate an error for these declarations:



extern int xs; // Oops! compiler error because xs is static.

extern void fs (); // Oops! compiler error because fs () is static.



So, the static modifier marks a global variable and function as internal and hidden to the other source codes (or modules).



3) (SUBJECT of YOUR QUESTION) a static keyword may be used as a modifier to a class member variable or function:



class A

{

public:

int xn;

void fn ();

static int xs;

static int fs ();

};



For simplicity, I assumed all of these members to be public. Being static has nothing to do with a member's accessibility (being private, protected or public).



Let's compare the non-static members A::xn, A::fn () with the static members A::xs and A::fs (). The non-static members, A::xn, A::fn () , are considered to be the property and method of an object of class A:



A objA;



objA.xn = 10;

objtA.fn ();



The static members, A::xs, A::fs (), are considered to be the property and method of the class A itself, not ant particular object or instance of this class. They are in fact shared among all the objects and instances of class A. We cannot access them like xn and fn above as being a member of an object. We could only access them as the member of class:



A::xs = 4;

A::fs ();



To use a non-static member of a class, we must first create an instance of that class, then access that member for that object created. To use a static member we do not need any class instance.

A good example of when we need a static member for our class is when we want to assign am automatic id number to our created objects:



class SomeClass

{

private:

static int auto_number;

int id_number ;

public:

SomeClass () { id_number = auto_number++; }

};



// A static member variable must be defined and initialized externally:

Int SomeClass::auto_number = 0;



Now, each time we create a new instance of class SomeClass, an automatic unique id is created for that object.



I hope this info is useful.
Emely
2016-02-29 00:43:31 UTC
Static doesn't mean unchangeable in this case (not the same as const), just that the variable doesn't change from instance to instance. This lets a programmer easily achieve some type of global synchronization between all instances of a class. The classic example is creating an ID that is unique for each class instance. The global ID is statically initialized to something like 0. Then as each instance is created it copies the current value of the static variable to a private id variable and then increments it so the next instance will get a different ID.
Chris C
2010-05-16 18:44:55 UTC
I've declared member variables and member functions as static.

I define them as static, if I only wan to have one instance of that variable and/or member function.



This is an easy way to provide a Singleton class.

Static variables defined as the same type that can be used for calculations.

Another reason is that you could include only maintaining a single pre-defined string (i.e. filename of your program's configuration, or filename of a central URL your application should connect to, etc.).

Of course, you could have a central piece of data (in memory, disk, url) but have several different programs utilizing the same information. Obviously you'd have to consider using semaphore's or something to handle the access to resources that are shared.
Jonas
2010-05-15 04:49:34 UTC
Some data aren't simply ideal to associate with object instances, e.g. class constants. If you have a class Math, you could have a constant PI = 3.14. It wouldn't be sane to have a constant for each object instance, when the number would be the same anyway.



Obviously, one of the best examples of where a static member is required, would be an implementation of a singleton (singletons are objects which one could only have one instance of).



Java code:



class Singleton {

    protected static Singleton instance = null;

    //...



    // protected constructor, so instances could only be created from "inside" the class

    protected Singleton() {}



    // Factory method

    public static Singleton factory() {

        if (instance == null)

            instance = new Singleton();

        return instance;

    }

}
2010-05-15 04:56:57 UTC
The reason for static members in a class is to reduce the memory required. For example if you had a class Math that had a member PI = 3.14 then every instance of Math would have to keep memory allocated for PI in case you decided to change or manipulate the data in that specific object, whereas if its static there is only one PI instead of many. Basically if you had 50 instances of the math object it'd have 50 spots in memory reserved for PI, making it static reduces that to 1 spot.
?
2010-05-15 05:03:28 UTC
If you declare an example of a class, like the above vehicle variable, the static member is not part of the object: the compiler creates and keeps up the static member, whether you use it or not, whether you declare a class variable or not.
Lav
2010-05-15 06:23:03 UTC
IN C,

static can be declared to variables,methods.

A static variable is global variable.

It can be accessed throughout the program.

A static method is called without any instance.

IN C++,OOPS...,

static is declared for variables,methods.

In java,.net main method is also static because it is called before creating an object.

A static variable is shared among objects.





IN C++,





#include

class example

{

private:

static int sum; //Static data

int x;

public:

example() //Constructor of the class

{

sum=sum+1;

x=sum;

}



~example() //Destructor of the class

{

sum=sum-1;

}



static void exforsys()

//Static function exforsys( ) defined with keyword static

{

cout<<"\nResult is: "<
}



void number() //Normal member function number( )

{

cout<<"\nNumber is: "<
}

};



void main()

{

example e1;

example::exforsys();

//Static function exforsys() accessed using class name example and the scope resolution operator ::

example e2,e3,e4;

example::exforsys();

e1.number();

//Normal member function accessed using object e1 and the dot member access operator.

e2.number();

e3.number();

e4.number();

}



In C,

#include



void foo()

{

int a = 10;

static int sa = 10;



a += 5;

sa += 5;



printf("a = %d, sa = %d\n", a, sa);

}





int main()

{

int i;



for (i = 0; i < 10; ++i)

foo();

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...