Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to manually call the constructor of a class in C++?

Tags:

c++

The most common way of creating an object of a class is by using the new keyword. It also calls the constructor. But if we used the malloc function to create the object, the constructor doesn't get called. Is it still possible to manually call the constructor after creating the object using malloc?

like image 511
reza.safiyat Avatar asked Sep 17 '25 11:09

reza.safiyat


1 Answers

It sounds like you want to call the constructor an a piece of memory created by malloc. This is possible and is called placement new

void* pMemory = malloc(sizeof(C));
C* pValue = new (pMemory) C();
like image 93
JaredPar Avatar answered Sep 19 '25 03:09

JaredPar