I am trying to get better at c++.
I have a Test class and below code in main().
Test *pObj = new Test();
If we debug by steping one by one instruction, First it goes to new function to allocate memory, then it calls constructor. Then it comes back to main() function. As we all know, constructor does not return anything. In that case, how come pObj will have the pointer which is allocated by new ? Any idea how it is implemented by compiler ?
When you use a
newexpression the compiler generates code to allocate memory and then call the constructor on the allocated memory to create a new object. If successful, it returns a pointer to the new object.Constructors have no return values, the compiler just adds a call to the constructor on a piece of memory where it needs the new object to be constructed. It’s not necessary for the constructor to return the location of the object, the code already knews where the object must be; it (effectively) passed it to the constructor.