Michael Zhou
Michael Zhou

Reputation: 497

What is wrong with this usage of the new operator?

Is this allowed?

Object::Object()
{
    new (this) Object(0, NULL);
}

Upvotes: 3

Views: 343

Answers (3)

bdonlan
bdonlan

Reputation: 231303

Using new(this) will re-construct member variables. This can result in undefined behavior, since they're not destructed first. The usual pattern is to use a helper function instead:

class Object {
private:
  void init(int, char *);
public:
  Object();
  Object(int, char *);
};

Object::Object() {
  init(0, NULL);
}

Object::Object(int x, char *y) {
  init(x, y);
}

void Object::init(int x, char *y) {
  /* ... */
}

Upvotes: 9

Khaled Alshaya
Khaled Alshaya

Reputation: 96879

I believe you want delegate constructors, like Java for example, which are not here yet. When C++0x comes you could do it like this :

Object::Object() : Object(0, NULL)
{

}

Upvotes: 2

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99635

If Object is a POD type you could initialize it in this way:

class Object
{
  int x;
  int y;
  // ...
public:
  Object() { memset( this, 0, sizeof Object ); }
};

Upvotes: 0

Related Questions