Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: call a constructor Message-ID: <381@taumet.com> Date: 4 Aug 90 20:49:06 GMT References: <1990Aug1.182945.23905@dg-rtp.dg.com> <9008031721.AA18726@zardoz.coral.com> Organization: Taumetric Corporation, San Diego Lines: 45 taylor@dg-rtp.dg.com (William Taylor) writes: > I would like to call a constructor directly on a piece of memory that > I have allocated. > I have a pointer to some memory (malloc'ed, shared memory, ...) > and I would like to put a class there. How can I call the constructor > for that class (and its base and member classes, etc.) to initialize > the memory? You cannot call a constructor directly. In version 2.0 and later, you can use a user-defined function "new" to get what you want. Here is a simple example: inline void * operator new(size_t, void *p) { return p; } class T { ... }; class U { ... }; void my_func() { T *t = ... // assign space for a T object U *u = ... // assign space for a U object ... new (t) T; // T constructor called new (u) U; // U constructor called ... } The "new" function takes a size_t parameter, and a pointer. Operator new takes an optional "placement" parameter in parens, shown here as (t) and (u). The placement is an address at which the object is already located. The effect is to bypass the storage allocation, and do everything else done by operator new -- such as call appropriate contructors. In this case, the constructor for type T (and for any base classes, etc) is called. The "new" function should probably static (here inline) to avoid conflict with other uses of various types and use of "new". It could also be a member function of the class. -- Steve Clamage, TauMetric Corp, steve@taumet.com