Explicitly calling the constructor



Hello !

I have a simple but interesting problem. I am using the 'malloc' routine to
reserve memory for a class object, and then trying to call the object's
constructor via the pointer returned. For some reason, this does not work at
all, and I have no idea why.

The reason why I need to do this is that I'm developing a COM component, and
in there it's suggested to use CoTaskMemAlloc to reserve memory instead of
the 'new keyword'. The object I'm trying to initialize is a complex class,
thus I need to call it's constructor.

Here is a code sample, to which Visual Studio .NET 2003 answers with error
C2273:

#include <stdlib.h>
#include <malloc.h>
#include <queue>
class CTestClass
{
public:
CTestClass()
{
m_nData = 0;
}
private:
int m_nData;
};

int main(void)
{
CTestClass* pData = (CTestClass*) malloc( sizeof(CTestClass) );

if ( pData )
{
pData->CTestClass();
free( pData );
}

return 0;
}


.



Relevant Pages

  • Why is my const pointer not behaving?
    ... Object ** obj; ... My query is if I changed the "const char *" to simply int as the ...
    (comp.lang.cpp)
  • Re: what is meant by ?
    ... the class in a context where you would normally use an int and the operator ... Conversion operators can be used quite generally. ... if you make a mistake and use a class object some place where you shouldn't, the conversion operator may allow the code to compile and thereby stop you from discovering the mistake. ...
    (microsoft.public.vc.language)
  • Re: Opinion on coding style.
    ... to use int with the same syntax you would use if you were constructing ... an class object using a specific constructor, to me seem like poor style. ... The above is the same syntax you might use if you were calling the DWORD ...
    (microsoft.public.vc.language)
  • Re: Are primitives objects?
    ... No, primitives are not objects. ... Every primitive type has it's own corresponding object type. ... int -> Integer, double -> Double, etc. ... > Class Object is the root of the class hierarchy. ...
    (comp.lang.java)