C ++ class construction and member initialization

The first seal shows the member is false and the other two are true. Why is the first result different from the last two?

#include <vector>
#include <iostream>

using namespace std;

class MyClass
{
public:
  bool value;
  bool stuff;
};

class Container
{
public:
  vector<MyClass> my_classes;
  Container()
  {
    MyClass c;
    cout << c.value << endl;
    my_classes.push_back(c);
  }
};

int main (int argc , char* argv[] )
{
  MyClass mc;
  cout << mc.value << endl;
  Container con;
  cout << con.my_classes[0].value << endl;
  return 0;
}

      

+2


source to share


3 answers


The two elements are primitive (non-class) objects and are thus uninitialized. This means that their values ​​will be arbitrary at run time. You must initialize them in the constructor:



class MyClass {
public:
  bool value;
  bool stuff;
  MyClass(): value(false), stuff(false) { }
};

      

+8


source


You are not initializing members with any value. They will only have some value that was in this place of memory before.



+3


source


The objects you declare in the main (..) are automatically allocated on the stack of the current thread. Since you are not initializing objects, they are simply filled with data that was previously in this very part of the stack.

If the processor is intel x86 architecture, the assembly language code for a typical function would look something like this (AT&T syntax)

pushl   %ebp 
movl    %esp, %ebp
subl    $LOCAL_VARIABLES_NUM * WORD_SIZE, %esp

...
<function code goes here>
<that is how we read variable values>
movl -4(%ebp), %ebx        
...

addl $LOCAL_VARIABLES_NUM * WORD_SIZE, %esp
popl %ebp

      

As you can see, we are simply adding and subtracting the required number of bytes from the stack pointer, leaving the old data where it was.

+1


source







All Articles