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

The most common way to create a class object is to use a keyword new. It also calls the constructor. But if we used a function mallocto create an object, the constructor will not be called. Is it possible to manually call the constructor after creating the object with malloc?

+3
source share
2 answers

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

void* pMemory = malloc(sizeof(C));
C* pValue = new (pMemory) C();
+7
source

You cannot directly call the constructor, like any other function, because the constructor does not have a name.

, , .

+2

All Articles