OOP static variable standards - c++

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?

Related

private static member function vs private member function

One can choose public static over private static if the static needs to be accessed outside the class(e.g. singleton), while private static is preferred when the function need not be exposed(otherwise unnamed namespaces would do fine) - in which case its only access either through static member function or other non static member functions
However i am trying to get to the core idea of why would one choose private static over private member function?
Ofcourse, both can have access to private members of the class(or any object that is passed), with static member explicitly requiring an object to be passed, but why can't i keep my design open by making it a private Non-Static member function even if it doesn't need access to private members(just like static member functions). This way even if in future i require to access some private members i save myself from converting static to non-static mem func - I understand this isn't a big deal/change but still can somebody give me a crystal clear idea about when and why to choose one over the other?
When you have a static member variable, you choose its access level in just the same way that you would for a non-static member variable. There's nothing "special" here.
Most of my private statics tend to be things like built-in constants that are only used by the internals of the class.
I admit I can't think of many other use cases for them, but I will also tend to make any function static if it logically has nothing to do with a particular instance of the class (and thus needs no non-static member access) — this may be a bit more OCD than some people indulge in though.
why can't i keep my design open by making it a private Non-Static member function even if it doesn't need access to private members(just like static member functions)
You can. It is up to you.
This way even if in future i require to access some private members i save myself from converting static to non-static mem func
Sure. I mean, it's one keyword. But this "forward-compatibility" may be useful if you need to keep your headers from changing (e.g. you're deploying them). Arguably this is a downside of making static members private, where there aren't really many solid upsides. Again, it's up to you.

Private vs. Static functions in C++

Is there any advantage to using private (probably also static) functions in a class for utility functions used in my class that do not need access to an instance's data over using global static functions in my .cpp file that implements the class?
The first sounds cleaner to me, but the second really makes more sense as these functions do not need to even be mentioned in the .h file.
I would not put private static functions to the header file if they are not needed. They would just pollute the header file and add more work.
But private static functions may be needed when you have a template method/function in a class and want to use that helper function in it.
Another reason for using private static functions instead of global static functions is that they can access private class members (variables, functions).
If a given function relates to your class then you are right. You should make them private static within your class body.
[Note: If those utility function doesn't relate at all then you can think about enclosing them in a namespace or another Util class and keep it within the file scope.]
Just make them file-static functions. If they don't have anything to do with the class, don't put them there.
If the private function doesn't modify the class members, it doesn't have any advantage over the global static. Being inside or outside the class makes no difference

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.

What are static variables?

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/

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?