C++, unlike some other languages, allows static data to be of any arbitrary type, not just plain-old-data. Plain-old-data is trivial to initialize (the compiler just writes the value at the appropriate address in the data segment), but the other, more complex types, are not.  How is initialization of non-POD types typically implemented in C++? In particular, what exactly happens when the function foo is executed for the first time? What mechanisms are used to keep track of whether str has already been initialized or not?  #include &lt;string&gt; void foo() {     static std::string str("Hello, Stack Overflow!"); }
24968
If a variable is declared as static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?  void foo()  {      static string plonk = "When will I die?"; }
115971
In the context of C++ (not that it matters):  class Foo{     private:         int x[100];     public:         Foo(); }   What I've learnt tells me that if you create an instance of Foo like so:  Foo bar = new Foo();   Then the array x is allocated on the heap, but if you created an instance of Foo like so:  Foo bar;   Then it's created on the stack.  I can't find resources online to confirm this.
65547
See also      Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.  #include &lt;map&gt;  struct MyClass {     MyClass(int t); };  int main() {     std::map&lt;int, MyClass&gt; myMap;     myMap[14] = MyClass(42); }   This gives me the following g++ error:     /usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’   This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax.
18652
I have the following class in C++:  class a {     const int b[2];     // other stuff follows      // and here's the constructor     a(void); }   The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const?  This doesn't work:  a::a(void) :      b([2,3]) {      // other initialization stuff }   Edit:  The case in point is when I can have different values for b for different instances, but the values are known to be constant for the lifetime of the instance.
57479
Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter?  Here's an example class:  class StringBuffer { public:     StringBuffer(std::string &amp; str) : m_str(str)     {         m_buffer.push_back(0);     }     ~StringBuffer()     {         m_str = &amp;m_buffer[0];     }     char * Size(int maxlength)     {         m_buffer.resize(maxlength + 1, 0);         return &amp;m_buffer[0];     } private:     std::string &amp; m_str;     std::vector&lt;char&gt; m_buffer; };   And here's how you would use it:  // this is from a crusty old API that can't be changed void GetString(char * str, int maxlength);  std::string mystring; GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);   When will the destructor for the temporary StringBuffer object get called?  Is it:   Before the call to GetString? After GetString returns? Compiler dependent?   I know that C++ guarantees that a local temporary variable will be valid as long as there's a reference to it - does this apply to parent objects when there's a reference to a member variable?  Thanks.
45361
What is the right way of initializing a static map? Do we need a static function that will initialize it?
7570
I noticed C++ will not compile the following:  class No_Good {   static double const d = 1.0; };   However it will happily allow a variation where the double is changed to an int, unsigned, or any integral type:  class Happy_Times {   static unsigned const u = 1; };   My solution was to alter it to read:  class Now_Good {   static double d() { return 1.0; } };   and figure that the compiler will be smart enough to inline where necessary... but it left me curious.  Why would the C++ designer(s) allow me to static const an int or unsigned, but not a double?  Edit: I am using visual studio 7.1 (.net 2003) on Windows XP.  Edit2:  Question has been answered, but for completion, the error I was seeing:  error C2864: 'd' : only const static integral data members can be initialized inside a class or struct
9790
If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements.  However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it.  Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?
42535
If I have a class as follows     class Example_Class     {        private:          int x;           int y;         public:           Example_Class()           {               x = 8;              y = 9;          }        ~Example_Class()         { }     };   And a struct as follows  struct {    int x;    int y; } example_struct;   Is the structure in memory of the  example_struct simmilar to that in Example_Class  for example if I do the following  struct example_struct foo_struct; Example_Class foo_class = Example_Class();  memcpy(&amp;foo_struct, &amp;foo_class, sizeof(foo_struct));   will foo_struct.x = 8 and foo_struct.y = 9 (ie: the same values as the x,y values in the foo_class) ?  The reason I ask is I have a C++ library (don't want to change it) that is sharing an object with C code and I want to use a struct to represent the object coming from the C++ library. I'm only interested in the attributes of the object.  I know the ideal situation would be to have Example_class wrap arround a common structure between the C and C++ code but it is not going to be easy to change the C++ library in use.
78860
The question was about plain  functions, not  static methods, as clarified in comments.  I understand what a static variable is, but what is a static function?  And why is it that if I declare a function, let's say void print_matrix, in let's say a.c (WITHOUT a.h) and include "a.c" -  I get "print_matrix@@....) already defined in a.obj", BUT if I declare it as static void print_matrix then it compiles?  UPDATE Just to clear things up - I know that including .c is bad, as many of you pointed out. I just do it to temporarily clear space in main.c until I have a better idea of how to group all those functions into proper .h and .c files. Just a temporary, quick solution.
82347
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?  Classic Example:  int i = 0; foo(i++, i++);   Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).
8220
I know that the compiler will sometimes initialize memory with certain patterns such as 0xCD and 0xDD.  What I want to know is when and why this happens.  When  Is this specific to the compiler used?  Do malloc/new and free/delete work in the same way with regard to this?  Is it platform specific?  Will it occur on other operating systems, such as Linux or VxWorks?  Why  My understanding is this only occurs in Win32 debug configuration, and it is used to detect memory overruns and to help the compiler catch exceptions.  Can you give any practical examples as to how this initialization is useful?  I remember reading something (maybe in Code Complete 2) saying that it is good to initialize memory to a known pattern when allocating it, and certain patterns will trigger interrupts in Win32 which will result in exceptions showing in the debugger.  How portable is this?
51146
Here is an example of polymorphism from  (edited for readability):  // abstract base class #include &lt;iostream&gt; using namespace std;  class Polygon {     protected:         int width;         int height;     public:         void set_values(int a, int b) { width = a; height = b; }         virtual int area(void) =0; };  class Rectangle: public Polygon {     public:         int area(void) { return width * height; } };  class Triangle: public Polygon {     public:         int area(void) { return width * height / 2; } };  int main () {     Rectangle rect;     Triangle trgl;     Polygon * ppoly1 = &amp;rect;     Polygon * ppoly2 = &amp;trgl;     ppoly1-&gt;set_values (4,5);     ppoly2-&gt;set_values (4,5);     cout &lt;&lt; ppoly1-&gt;area() &lt;&lt; endl; // outputs 20     cout &lt;&lt; ppoly2-&gt;area() &lt;&lt; endl; // outputs 10     return 0; }   My question is how does the compiler know that ppoly1 is a Rectangle and that ppoly2 is a Triangle, so that it can call the correct area() function? It could find that out by looking at the "Polygon * ppoly1 = &rect;" line and knowing that rect is a Rectangle, but that wouldn't work in all cases, would it? What if you did something like this?  cout &lt;&lt; ((Polygon *)0x12345678)-&gt;area() &lt;&lt; endl;   Assuming that you're allowed to access that random area of memory.  I would test this out but I can't on the computer I'm on at the moment.  (I hope I'm not missing something obvious...)
38527
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the .  However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the __new__ which feels quite hacky.)  Here's an example:  class A(object):     _dict = dict()      def __new__(cls):         if 'key' in A._dict:             print "EXISTS"             return A._dict['key']         else:             print "NEW"             return super(A, cls).__new__(cls)      def __init__(self):         print "INIT"         A._dict['key'] = self         print ""  a1 = A() a2 = A() a3 = A()   Outputs:  NEW INIT  EXISTS INIT  EXISTS INIT   Why?
3852
Is a string literal in c++ created in static memory and destroyed only when the program exits?
21989
Very simply put:  I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.  Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.  class test  { public:     static unsigned char X;     static unsigned char Y;      ...      test(); };  test::test()  {     X = 1;     Y = 2; }   I'm new to C++ so go easy on me. Why can't I do this?
109558
Are these two equivalent?  char * aString = "This is a string.";  char aString[] = "This is a string.";  From my understanding, C++ stores strings by their addresses, so the pointer is getting a valid address. I assume the strings are also stored as type char? But how does it know how much memory to allocate for the string? Normally, char arrays need their array size preset. I believe the [] type arrays are counted by the compiler before compilation. Is this what happens for the string literal pointer as well?  On to my second question, what is the difference between these two:  int someNumber;  int * someNumber = new int;  The second is supposed to be dynamic allocation. If I understand the concept right, it allocates the memory as soon as it reads the declaration. But what happens in the standard declaration? Basically, I need to understand how dynamic allocation is advantageous over standard declarations.