Reputation: 12791
Does new
in C++ call a constructor behind the scenes? Or is it the other way around?
I have seen code like new MyClass(*this)
which confuses me, since I didn't know that new
could take arguments.
Maybe that's because new
can call a constructor and, as a result, it can take the arguments declared by a constructor?
Upvotes: 1
Views: 226
Reputation: 212
There is a difference between new
and operator new
.
The new
operator uses a hidden operator new
function to allocate memory and then it also "value-initializes" the object by calling its constructor with the parameters after the class name.
In your case you call new
which allocates memory using ::operator new()
and then it initializes an object of MyClass
class in that memory using a constructor with the parameter *this
.
#include <iostream>
class A {
public:
int m_value;
A(int value): m_value(value){};
};
int main (){
int *a = new int;
auto b= new A(1);
std::cout << *a << std::endl;
std::cout << b->m_value << std::endl;
printf("%02x ", *b);
}
Program returned:
0
15
0f
As you can see, the new
for the a
variable creates only a pointer that is value-initialized to 0. That's why when we dereference it we have 0 (all bit all 0, int is 4 bytes most of the time and the pointer point to a memory content = to 0x0000)
But for the b
variable we pass parameters. And if we look at the memory content of the b
object we can read 0f
which means it contains 15 (the member value)
Upvotes: 3
Reputation: 96810
MyClass(*this)
creates an object of type MyClass
by calling its constructor and passing *this
as an argument. Putting new
behind it means the object is allocated on the heap instead of the stack. It's not new
which is taking the argument, it's MyClass
.
Upvotes: 4
Reputation: 2981
This is not new
taking arguments, it's the constructor taking arguments.
Upvotes: 0