Static member variables [duplicate] - c++

This question already has answers here:
When are static C++ class members initialized?
(7 answers)
Closed 8 years ago.
I started using C++ for object oriented programming and I've come across static member variables.
In my particular case, I have the following in my header file (Class.hpp):
private:
const static string DEFAULT_PATH;
static string path;
Not that really matters, but is as valid as any example.
So, to do the proper initialisations I had to do some research and find out that this can't be done in the class body and has to be done in the source (Class.cpp) file. In my source file, I added:
const string Class::DEFAULT_PATH = "./";
string Class::path = DEFAULT_PATH;
I found this to be counter-intuitive, but tried to deal with it. Then I wondered:
When exactly did the compiler call this initialization code? How can I assume when will this fields have a value? I don't really understand what's happening there and I'd like to know.
And what's most intriguing for me: which symbols can I see whithin Class.cpp when including class.hpp? And why those declarations have be outside the class body and in another file?

Static members are initialized before the main starts, so they are already initialized in your main. Non static members of the class are initalized in the constructor.
If you want to enforce the initialization order (which is the case because one variable refers to the other), you can use a function to initalize the function C++ static initialization order.
boost::call_once (or its c++11 equivalent) can help you for that. http://www.boost.org/doc/libs/1_31_0/libs/thread/doc/once.html
The standard tells you that it has to be initalized somewhere outside the class definition, so generally you do it on the cpp file
Once this is done you can access the variables with Class::static_member

Related

When and why would I use a constant function in C++ [duplicate]

This question already has answers here:
Why use a const member function?
(3 answers)
What are the semantics of a const member function?
(9 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Edit: From #Jeremy Friesner's answer, he provides another view point that Why use a const member function & semantics of a const member function don't cover. It can improve clarity and disambiguous your code. People can have a brief idea of what this function is supposed to do or not do at the first glance. Very useful especially in working with others.
I come across the constant function lately.
It says:
Constant functions are those have denied permission when attempting
to change the member variables of their classes.
My questions are
In a programmer perspective, if you don't want a function being able to change member
variables, why not just moving the parts responsible for changing variables outside
of the function at the first place? (e.g using another function)
What/when are some practical moments of having the neediness to use a constant
function?
Appreciate any answers
class Foo
{
public:
int x = 0;
int Bar(int arg) const
{
x++; // fails
return x; // okay
}
};
The purpose of const-tagged methods isn't to prevent the programmer from intentionally modifying member variables, but rather to allow the compiler to assist the programmer by producing a compile-time error when the programmer accidentally modifies a member-variable. This is useful because it's much easier and quicker to correct a compile-time error than to chase down a run-time misbehavior through manual testing.
The const tag also assists later programmers who are reading the class's header file by helping them quickly understand what a method does or does not do. For example, if you see this in a class declaration:
class MyClass
{
[...]
int CalculateTheValue();
... you might ask yourself, "does calling CalculateTheValue() change the state of the MyClass object?" With a name like CalculateTheValue() it seems like it shouldn't, but there's no way to know for sure without finding the corresponding .cpp file and reading through the code that implements that method... which is a tedious and error-prone way to do things.
On the other hand, if you see this:
class MyClass
{
[...]
int CalculateTheValue() const;
... then you know right away that CalculateTheValue() will not modify the MyClass object you call it on, because it says so in the declaration. (if it did try to modify the MyClass object, the code wouldn't compile; so if the code compiled, we know it doesn't modify it)

how to call functions from header file [duplicate]

This question already has answers here:
What is this weird colon-member (" : ") syntax in the constructor?
(14 answers)
Closed 5 years ago.
CWmcaIntf::CWmcaIntf() :
m_hDll(NULL),
m_pLoad(NULL), m_pFree(NULL), m_pSetServer(NULL), m_pSetPort(NULL), m_pIsConnected(NULL),
m_pConnect(NULL), m_pDisconnect(NULL), m_pTransact(NULL), m_pQuery(NULL), m_pRequest(NULL), m_pAttach(NULL),
m_pDetach(NULL), m_pDetachWindow(NULL), m_pDetachAll(NULL), m_pSetOption(NULL),
m_pSetAccountIndexPwd(NULL), m_pSetOrderPwd(NULL), m_pSetHashPwd(NULL), m_pSetAccountNoPwd(NULL), m_pSetAccountNoByIndex(NULL)
i dont know what this grammer means. i am trying to use a header file 'CWamInf'. and want to know different methods or problems .. thanks..
I don't know how much you know about headers classes and stuff so I'll try to explain everything I can.
CWmcaIntf::CWmcaIntf() :
The CWmcaIntf:: means that the function that is about to be defined after the double colon is within the class "CWmcaIntf".
The CWmcaIntf() is a constructor : it has the same name as the class and its purpose is to construct each object of a class depending on the code you put in it. I'd say that often, its only purpose is to initialize member variables. If it isn't clear yet, check this link.
m_hDLL(NULL)
As you most certainly know, programmers tend to respect and harmonize on coding conventions. One of those is to name all member variables by m_something, so your code become easier to understand for you and everyone else.
So here, all you got is a constructor initializing a lot of member variables to NULL, which means that when a CWmcaIntf object will be constructed, its member variables will be equal to nothing and only be modifiable with setters if data are properly encapsulated.
Now if the purpose of your question was for us to tell you more about what does mean the member variables, and what the constructor may do, well don't expect an answer since zero details ae given and nothing even matches the tutorial explaining how to properly ask a question.

difference between static and non static recursive member [duplicate]

This question already has answers here:
static class member of class's own type [duplicate]
(2 answers)
Closed 6 years ago.
The C++ programming language book mentions like below:
It is not possible to declare new objects of a struct until its complete declaration has been seen. For example:
struct No_good {
No_good member; // error : recursive definition
};
This is an error because the compiler is not able to determine the size of No_good.
But below piece of code is compiling for me.
struct No_good {
static No_good member; // OK: compiling
};
how static keyword allowing compiler to know the size of member. AFAIK static decides the storage class of a named variable.
The reason you can't have a full No_good member inside the No_good class, as pointed out by Francois Moisan is because it would be infinitely recursive and take infinite space.
A No_good* member would be ok because it has a finite space(size of a pointer) and can be null stopping the recursion.
A static member is also ok becuase it is not stored in every instance of No_good but instead shared by all of the instances. It is not technically part of the object but something associated with the namespace of No_good.
Hope this clears it up.
You can think the static variable as a global variable. Only difference is it is under the class's namespace. So if it was a global variable you could reach it like No_good but if it is static you have to type No_good::No_good. You can do that even you never instantiate the class.
The same troubles you can get into with globals you will get with statics as well. You never know which static variable initializes first if they depend on each other you are still in trouble.
The way I experience it, lots of statics usage comes from writing C++ code with C point of view.

Creating a static field in header file | C++

I am working on an assignment, and while I don't have any issues with the actual assignment, I want to make my code "proper." I am trying to define a static variable in my header file. I want it to be static so that all instances of this class can access the same variable. I don't want to extern it either, I want just this class to have access to it.Then I am trying to define it in the actual file (not header) but I keep getting an error about not being able to cast. I just want to learn how to properly do this to have cleaner code.
The definition of your field stays inside the class:
class AddrSpace
{
List *availSpots;
};
The full name of this variable will be AddrSpace::availSpots. C++ requires to define static variables (including the static fields of the classes) explicitly. I would not say this is fully logical because compiler already has everything to generate all necessary stuffs. Nevertheless this is so. The definition in your C++ file should look like:
List *AddrSpace::availSpots = new List();
Next time please add the source directly into the question.

Since static member functions can't modify non-static member variables, why should we still use it? [duplicate]

This question already has answers here:
When to use static member function? [duplicate]
(7 answers)
Closed 9 years ago.
I know static class member function don't need to be instantiated. But, since class member functions' manipulation are always based on its' own member variables, why we still use the static member functions? can someone tell me by some detail examples? Thanks in advance.
P.S. I am writing a program that in one class member function create two threads, so that I need to pass the thread callback function address to when create the two threads. I want the thread callback function also be the same class's member function. According to some references, if a callback function is a class's member, it should be static. There comes the question: in the static callback, I can't call other non-static function in the same class, and can't modify it's non-static member variables. (English is my secondary language, so I'am not good at it. hope some help me describe it more succinctly:-)
I will just give you an example. If you want to calculate how many instances you have declared about your class, you may have a static member like
int instance_count;
and in the class constructor you can add the instance_count like:
instance_count++;
and in your destructor :
instance_count--;
As a result, you can get how many instances you have currently in your program.