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)