tags:

views:

100

answers:

2

Possible Duplicate:
How to prevent an object being created on the heap?

Hi,

I heard a concept called as stack based class. I.e. we can’t create instance of the class using new.

I am hearing this for the first time. One way to implement this by private overloading of ‘new ’ operator.

If anybody know details about the stack based class please inform me.

A: 

Instead of overloading new operator follow the Factory pattern.

  • A static method to create new instances of this class.
  • An access method to get the last instance (from the top of stack)
Ankit Jain
I've been hearing a lot about using factories instead of overloading "new" recently... why is this?
xitrium
''An access method to get the last instance (from the top of stack)'' ---- ??? Can you explain this more detailed?
IanH
+2  A: 

It's all in the instantiation:

AnotherClass::SomeMethod(...) {
  MyClass stackBased;
  MyClass *heapBased;

  *heapBased = new MyClass();
  *heapBased->DoSomething();
  delete heapBased;

  stackBased.DoSomething();

  ...
}

A stackbased class is automatically allocated, instantiated and deallocated on the stack, whereas you need to do it all by yourself for a heapbased.

Claus Broch
That's not the question. The question is, how would you stop your code snippet from compiling? What do you do to `MyClass` such that "we can’t create instance of the class using new" (to quote the question above).
Daniel Earwicker
Sorry, misunderstood the question. But in that case then this question is a possible duplicate as KennyTM noted.
Claus Broch