Instantiation of an Object only thru "new Operator"

M

Mysooru

How to restrict an object to be instantiated only using new operator?

I mean, one should not be allowed to create an object like AnObject obj; it
should be AnObject obj = new AnObject;
 
J

John Harrison

Mysooru said:
How to restrict an object to be instantiated only using new operator?

I mean, one should not be allowed to create an object like AnObject obj; it
should be AnObject obj = new AnObject;

Make the constructor private and write a static member function that uses
new

class AnObject
{
public:
static AnObject* createAnObject(); { return new AnObject(); }
private:
AnObject(); // private ctor
};

AnObject* obj = createAnObject();

john
 
J

Jonathan Mcdougall

How to restrict an object to be instantiated only using new operator?
Perhaps because the object wants to do a "delete this;"?

Isn't it allowed to do it even if it is an automatic object (assuming
a placement new will be made) ?

Jonathan
 
J

John Harrison

Jonathan Mcdougall said:
Isn't it allowed to do it even if it is an automatic object (assuming
a placement new will be made) ?

Jonathan

You can't delete this on an automatic object. What does placement new have
to do with anything?

john
 
J

Jonathan Mcdougall

You can't delete this on an automatic object. What does placement new
have

Quote '(assuming a placement new will be made)'.

Just trying to understand your point, not pick an argument. Perhaps you
could illustrate with some code.

I think irony does not travel very well through cable modems.

I don't know why I said that, I even started an answer like

class A
{
public:
void f()
{
delete this;
this =

and then

const_cast<A*>(this) =

and worst

const_cast<A*>(this) = new (this) A;

before understanding the profound stupidity of my point. I then made
a joke, hoping nobody would notice. Too bad :)

Sorry about that,


Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top