New operator in C ++
I am reading Chapter 13 Thinking in C ++. The following follows from the book.
MyType * fp = new MyType (1, 2);
at runtime, which is equivalent to malloc (sizeof (MyType)) is called, and the constructor for MyType is called with the resulting address as this pointer , using (1, 2) as the argument list. By the time the pointer is assigned to fp.
I am confused by the bold proposal. What does it mean?
This is a very light explanation, but it basically says that the result is a memory location like and malloc
, and at that memory location an object this
is created ( is a pointer to the current object) using a constructor with that argument list.
When an operator new
allocates memory dynamically, it returns a pointer to that memory (similar to how it malloc()
works in C).
In C ++, every non-static method has access to the current object it is called on (otherwise, C ++ programmers around the world will have serious problems). This is an "implicit argument" for methods, also in constructors, and can be accessed via a keyword this
.
What the sentence means is that after the object is created, the operator will call the constructor in the newly allocated memory. Because that's the only thing that makes sense. :)