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

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.

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.

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?

Do C++ objects have the class's static methods?

I have a class that I'm refactoring it and would like to add a helper function to eliminate some code duplication in both static and non-static methods, so the helper function must be static. When I go to call the helper function from inside the non-static method, will I need to use the double colon notation, MyClass::helper_function(x, y, z), the arrow notation, this->helper_function(x, y, z), or just helper_function(x, y, z)? If the helper function was public would you be able to access it from an instance with the dot notation, myObject.helper_function(x, y, z)? I'll try it out in a couple of minutes, and I'm sure I'll figure it out, but I thought it was a good gedankenexperiment to try to figure out what will happen.
Should I just make the helper function not a member of the class at all, but just put it in the class's .cpp file to make it accessible to the class's methods? What is the best practice?
All three formats work.
MyClass::helper_function - this is a Qualified Name. The class name is looked up first, finds the current class, and then the static method is found in the class.
helper_function - this is an unqualified name. it will be looked up in the class scope first, before the surrounding scope would be tried. But since helper_function is a static method in the class, no further searches are done
this->helper_function - This is the most unusual of all. The this pointer has type MyClass*, so the search is restricted to MyClass. But once helper_function is found, it turns out that the this pointer isn't actually needed. That doesn't invalidate the name lookup.
Class member or not?
A static helper function may access other class members, in particular private members. This includes private constructors, private destructors, private nested types, constants, etc. If you need one of them, a static method is the only reasonable choice.
Yes, you can access static methods by way of the this pointer and the . or -> notation.

Unnamed namespaces vs private variables

I have been reading through other questions on here and there is something that has me confused and hopefully it can be explained. I am sure there it is a simple thing but it is alluding me.
So in C++ we have private variables that are only viewable within the class:
class MyClass
{
private:
int i;
};
But we can also have unnamed namespaces:
namespace
{
int i;
}
Both appear to be private to the class but in the 2nd case you cannot see they exist from the header file. From reading other questions it seems that functions are different as you can't pass class objects to them? But I am not sure what the difference is here for variables.
Is there a disadvantage to the 2nd way that means you should still use private variables?
They aren't the same.
Integer i in the anonymous namespace will be shared by all instances of MyClass.
The private integer i in MyClass will be unique for each instantiation of the class.
The equivalent using private would be to make i static:
//.h
class MyClass
{
private:
static int i;
};
And instantiate the one single shared i like this:
//.cpp
int MyClass::i = 0;
Both appear to be private to the class ...
No, only the first is private to the class. It's a non-static member variable; one is instantiated in every object of the class type.
The second is not in a class at all; it has static storage duration, so one is instantiated for the whole program. Anything that accesses it is accessing the same variable as anything else that accesses it. Being in an unnamed namespace, it's only accessible within the translation unit (i.e. the source file) that defines it; but it's accessible to any code there, not just a particular class.
Is there a disadvantage to the 2nd way that means you should still use private variables?
If you want a copy of the variable in each class object, then you need it to be a non-static member.
If you want to share it between all objects, then it's up to you whether to make it a static member, or put it in a namespace inside the class's implementation file. I often do the latter to simplify the class definition. Disadvantages are that access isn't restricted just to the class but to anything else in that file, and you can't access it from any code that you might want to put in the header.
Namespaces are unrelated to objects/classes. In particular, if you have two objects, each has its own copy of a private variable.
They are quite different concepts. The private data member is visible only to a class, and in the non-static case, each class instance owns one of these. The anonymous namespace allows you to make code available only to other code in the same file. So in the case of the single int variable, all code defined in the same place as the anonymous namespace would see the same, single variable.

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?