The closest thread to my question is here. I am trying to compile the following code with gcc:
#include <malloc.h>
class A
{
public:
A(){};
~A(){};
};//class A
int main()
{
A* obj = (A*) malloc( sizeof(A) );
if(obj==0) return 1 ;
obj->A::A(); /*error: invalid use of 'class A' */
obj->A::~A();
free(obj);
return 0;
};//
From the command line I compile the code with:
$ g++ -o main main.cpp main.cpp: In function 'int main()': main.cpp:22: error: invalid use of 'class A'
Can you please point me in the right direction?
You can’t call a constructor on an object; a constructor can only be called in the creation of an object so by definition the object can’t exist yet.
The way to do this is with placement
new. There’s no need to cast yourmallocreturn. It should bevoid *as it doesn’t return a pointer to an A; only a pointer to raw memory in which you plan to construct anA.E.g.