Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialization of objects in c++

I want to know, in c++, when does the initialization of objects take place?
Is it at the compile time or link time?
For ex:

//file1.cpp
extern int i;
int j=5;

//file2.cpp ( link with file1.cpp)
extern j;
int i=10;  

Now, what does compiler do : according to me, it allocates storage for variables.
Now I want to know :
does it also put initialization value in that storage or is it done at link time?

like image 828
Happy Mittal Avatar asked Nov 05 '22 12:11

Happy Mittal


1 Answers

Actually there are different cases:

  • global variables or static variables (not classes): these values are stored in an init section of the exe/dll. These values are created by the linker based on the compiled object files information. (initialization on loading + mapping the dll/exe into memory)
  • local non static variables: these values are set by the compiler by putting these values on the stack (push/pop on x86) (compiler initialization)
  • objects: memory is reserved on the stack, the actual setting of values is deferred to the call to the constructor (run-time initialization)
  • pointers to objects (not actually a new case): space is reserved for the pointer only. The object pointed to exists only after a call to new that reserves memory and calls the constructor to initialize it (run-time initialization)
like image 65
jdehaan Avatar answered Nov 12 '22 17:11

jdehaan