Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new operator in c++

I'm reading the chapter 13 of "Thinking in c++". The following comes from the book.

MyType *fp = new MyType(1, 2);

at runtime, the equivalent of malloc(sizeof(MyType)) is called, and the constructor for MyType is called with the resulting address as the this pointer, using (1, 2) as the argument list. By the time the pointer is assigned to fp.

I'm confused by the bold sentence. What does it mean?

like image 275
Fihop Avatar asked Sep 17 '25 22:09

Fihop


2 Answers

It's a very loose explanation, but it's basically saying that the result is a memory location, just like malloc would return, and at that memory location an object is constructed (this is a pointer to the current object) using the constructor with that argument list.

like image 74
Luchian Grigore Avatar answered Sep 20 '25 10:09

Luchian Grigore


When the new operator allocates memory dynamically, it returns a pointer to that memory (similar to how malloc() works in C).

In C++, every non-static method has access to the current object it is called on (else C++ programmers around the world would be in serious trouble). This is an "implicit argument" of the methods, in the constructors as well, and one can access it through the keyword this.

What the sentence means is that after creating the object, the operator will call the constructor on the memory it just allocated. Because this is the only thing that makes sense. :)


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!