What are static variables? - c++

What are static variables designed for? What's the difference between static int and int?

The static keyword has four separate uses, only two of which are closely related:
static at global and namespace scope (applied to both variables and functions) means internal linkage
this is replaced by unnamed namespaces and is unrelated to the rest
in particular, others tend to imply some sort of uniqueness, but internal linkage means the opposite: you can have many objects with the same name, as long as each has internal linkage and you only have one per translation unit
static data members are "shared" among all instances of the class
it's more like they are independent of any class instance
this is sometimes grouped with static methods
static methods do not "operate" on a current instance
no this pointer; can call without an instance
static local variables (in functions) persist across the scope of each function call
Both static data members and static local variables can become hidden global state, and should be used carefully.
Now which two are closely related? It's not the two class members—the warning about global state gives it away. You can consider static data members as static local variables, where the functions to which they belong are all methods of the class, instead of a single function.
I found many related questions, but, surprisingly, no duplicates.

Static variables are initialized in the data segment (on x86; modify as appropriate for other architectures) instead of on the stack. They persist for the life of the program instead of vaporizing once they go out of scope.

A static member can be referenced without an instance.
See the "Static Members" section here: http://www.cplusplus.com/doc/tutorial/classes2/

Related

Calling member function without creating object in C++

Can anyone explain why we can call static member functions without creating instance of an object but we can't in case of non-static functions?
I searched everywhere, I couldn't find an explanation, Can you help?
You've got the logic basically in reverse. It is useful to have functions that belong to a class, even though they do not need to be called on an object of that class. Stroustrup didn't want to add a new keyword for that, so he repurposed the existing keyword static to distinguish such methods from normal methods.
In hindsight, other options could have been chosen. We could have made this an explicit function argument for the normal methods, for instance. But that's about 30 years too late now.
Why?
Because we like encapsulation and modularity which we get when using object orientated patterns.
You can view static class member functions and variables as a way of encapsulating what would otherwise have been global functions and variables - which might collide.
Underneath, there is not a great deal of difference between a plain old C++ file with some functions declared and implemented in it, to a class filled with only static functions. The difference is we can cleanly access a set of functions attached to a parent class.
An example:
Suppose you want to create a new class like MyMediumInteger, and you want developers to determine what the maximum number it can hold is. This information is applicable for every instance of MyMediumInteger, no matter what the state of the private member variables are. Therefore it makes sense to expose this information without forcing the developer to instantiate the class. Your options include defining something global such as #define MYMEDIUMINTEGER_MAX ... which could collide with a define sharing the same name in another module, or create a static function returning the max size, called neatly via
MyMediumInteger::maxSize().
A code example:
/***
* Use a static class member function (or variable)
*/
class MyMediumInteger
{
public:
static unsigned long maxSize() { return pow(2, 32) - 1; };
};
auto maxSize = MyMediumInteger::maxSize();
/**
* Alternative approaches.
* Note: These could all collide with other #defines or symbols declared/implemented in other modules.
* Note: These are both independant sources of information related to a class - wouldn't it be nicer if they could just belong to the class instead?
*/
/***
* Use a #define
*/
#define MYMEDIUMINTEGER_MAX (pow(2, 32) - 1)
auto maxSize = MYMEDIUMINTEGER_MAX;
/**
* Use a global function or variable
*/
static unsigned long getMyMediumIntegerMaxSize()
{
return pow(2, 32) - 1;
}
auto maxSize = getMyMediumIntegerMaxSize();
A word of warning:
Static member variables and functions have some of the pitfalls of global variables - because they persist through instances of classes, calling and assigning to them can cause unexpected side effects (because static member variables get changed for everyone, not just you).
A common pitfall is to add lots of static member functions and variables for management - for example, maintaining a list of all other class instances statically which gets appended to in the constructor of each class. Often this type of code could be refactored into a parent class whose job it is just to manage instances of the child class. The latter approach is far more testable and keeps things modular - for example, someone else could come along and write a different implementation of the management code without appending to or re-writing your child class implementation.
How?
In C++ class member functions are not actually stored in class instances, they are stored separately and called on instances of classes. Therefore, it's not hard to imagine how static functions fit into this - they are declared in the same way as normal class member functions, just with the static keyword to say "I don't need to be given a class instance to be run on". The consequence of this is it can't access class member variables or methods.
Static member functions does not need a "this" pointer, it belongs to the class.
Non-static functions need a "this" pointer to point out in which object it belong to, so you need to creat a object firstly.
Because that's what static means: "I don't want this function to require an object to work on".
That's the feature. That's its definition.
Any other answer would be circular.
Why is it useful? Sometimes we want to be able to "organise" some data or utilities in our classes, perhaps for use by external code or perhaps for use by non-static functions of the same class. In that sense there is some crossover with namespaces.

OOP static variable standards

I am working on a project in C++ but I can see this happening in any other Object Oriented Language. I need a static variable in a class and I am wondering if the standard rules apply to static variables as to non-static variables in that within a class they should be private and changed/accessed with accessors and mutators of any variable of that type rather than being public and accessed directly by code outside the class. My gut tells me that static variables in a class should still be private but most code that I have searched for the answer to (generic static variable examples) have had the static variables public.
Since I am assuming that static variables should be private, what are some, if they exists examples of when a static variable in a class should be public?

memory layout of two C++ classes sharing the same members

Suppose I have a class X such that all its non-static members are PODs, and a class Y that has the same members in the same order as X, and is also POD itself. Is it legal to reinterpret_cast an instance of Y to X? If it's not, will it work in practice across platforms?
To give you a bit of background, my class X has itself as static members for convenience (i.e. class X { ... public: static const X& a; static const X& b; }, and I want to remove static initializers without changing the API. My plan was to create global static objects of Y type and reinterpret_cast them to X -- since all members are POD, I don't need constructor to be run.
Assuming the layout of the members are exactly the same and you are not introducing any inheritance you can "safely" reinterpret_cast. I put "safely" in quotes for a reason, doing this seems simply a bad idea, you say you want to
...remove static initializers without changing the API. My plan was to create global static objects...
Why would you do this? Keeping a set of static variables in a class has only one drawback, you have to type the name of the class whenever you use it. Also adding the static keyword to a global variable doesn't behave the same as in a class declaration. static when appended to a global variable means that the compiler will only use it in the scope of the translation unit. This means that you could potentially have multiple globals with the same name in separate files. Again this is only adding to the complexity, though you did not specify why you want to do this exactly, i can safely say that what you are trying to accomplish should be and could be solved in a much more scope-oriented fashion.

How to properly pass the value of a static member variable?

In C++, I have a static member variable in a class.
Then I pass this static member variable to a array of struct initialization. Now my problem is the value of that member in struct is gone.
Please explain if I'm missing some understanding about a static member variable. Did a static member have a limitation of passing its own value?
Please advice.
Many thanks
A static member variable is like a regular global except that:
Its name is scoped to that of the class in which it is a member. The class acts like a namespace, but in a more powerful way as it can be used in templates.
It can be protected or private in which case only those that have access to the class can access the member.
There is one instance of this, not one per object.
Private static member variables can usually be replaced with a "hidden" variable of the same type in the anonymous names of the compilation unit for the class. This is a preferable option as you then do not need to expose the implementation of your class (which is what private members usually are) in the header.
It would be useful to give an example that duplicates your error so we can see exactly what you are trying to do and why it does not work.

C++ static member functions and their scope

I have two questions.
In C++, a static member function has direct access to a public non-static data member defined in the same class?
False
In C++, a non-static member function has direct access to a private static data member defined in the same class?
True
My note say false for the first question and true for the second one. I just cannot find out why? Can you explain why this is? Thank you.
P.S. I'm studying for my final and I cannot seem to figure out why.
Everyone's in agreement, but should be very careful about their wording, because actually static member functions do have access to public non-static data members. For that matter, they have access to private non-static data members too. They just need an object to operate on, to access its members. This could be a parameter, or a global, or created in the static member function, or acquired via one of those things.
The following code is fine:
class foo {
public:
int a;
// static member function "get_a" ...
static int get_a(foo *f) {
// ... accesses public non-static data member "a"
return f->a;
}
};
So we ask ourselves, what's the difference between "access" and "direct access"?
I guess what's meant by "direct access" here must be "using only the name of the data member, without specifying an object". Everyone always needs to have an object in order to access non-static members - that's what non-static means. Non-static member functions just don't have to mention which object if they don't want to, because this is implicit. Hence their access to non-static data members can be direct.
The reason non-static member functions have direct access to private static data members is firstly that the code is in a member of the class, hence it can access private data members. Second, you never need an object in order to access static data members (you can specify one if you want, but all that's used is the static type of the expression, not the actual object), hence the access is direct.
Here's a hint: Recall that a "non-static data member" refers to a data member of a particular instance of your class. A static member function does not run in the context of any particular instance.
Static member functions cannot access instance variables (non-static data), because instance variables need an instance of the class to operate on.
Remember that static data members or functions are defined and allocated once (not per instance), and hence can be accessed by non-static functions just as you would access global variables, etc.
(Internally, static functions don't get passed a this pointer like regular member functions. I.e. they use a different calling convention. Due to this they can't reference this->foo which is what really happens when you reference a member foo in a member function.)
Many object oriented pundits/pandits would tend to silently say, you've got it wrong.
Wrong, not because the answer is wrong but the thinking process needs to be resequenced.
Let's say you are a submarine designer. You have designed the Nehru class submarine. You have the blue prints but not the submarines. On blue print of Nehru class, you have the designer's name - Sonia Gandhi. So now people could STATICally refer to Nehru->designer which yields the value "Sonia Gandhi".
Now, every submarine has a captain. Since no submarine has been built yet, you cannot refer to any captain and therefore the reference Nehru->captain is not logical.
Then you build 10 Nehru class submarines, each assigned a captain. Some of the submarines are the Mumbai, the Delhi, the Rafael Jacob, the Rishi Kapoor.
You still cannot refer to Nehru->captain to get any of the ten captains' names. You could say Delhi->captain, Mumbai->captain or Rishi Kapoor->captain and get the respective captain's name, but there would not be any such valid reference as Nehru->captain because the Nehru reference is a class design and not a ship.
However, you could refer to Delhi->designer or Mumbai->designer or Rafael Jacob->designer which will yield "Sonia Gandhi" just as Nehru->designer would.
There, got it?
In addition to Greg Hewgill's answer, you can think of the static functions as having a more narrow scope - i.e. member functions have access to everything static functions do AND all the instance variables. Static functions though can only access static members, which is logical enough.
class MyClass {
static int m_iStatic;
int m_iInstance;
static void StaticFunc() {
m_iStatic = 8; //OK
m_iInstance = 8; //not OK
}
void InstanceFunc() {
m_iStatic = 8; //OK
m_iInstance = 8; //OK
}
}
In C++, a static member function has
direct access to a public non-static
data member defined in the same class?
False
Static member functions cannot access non-static data of the class due to the fact that static member function is not bound to the instance. For that matter static function can be accessed without any object. Any object specific data cannot be accessed in static member function.
In C++, a non-static member function
has direct access to a private static
data member defined in the same class?
True
Again, since static data member does not belong to any particular object it can be accessed by all instances of the class.
to make things easier, lets strip the public/private away.
To access data member (attribute) of an object, you will need to know who/where is the 'object'.
A static member function are shared across among objectS so it will need additional information when you ask him to grab the data member.
image object as family, child is the data member, boardSchoolBus is the static function.
every children can board the school bus, but if you asked school bus to fetch a child, it would need to know which family to go right?