1

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.

Community
  • 1
  • 1
Umesha MS
  • 2,861
  • 8
  • 41
  • 60

2 Answers2

3

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
  • 9,212
  • 2
  • 29
  • 38
  • 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 Aug 19 '10 at 12:05
  • Sorry, misunderstood the question. But in that case then this question is a possible duplicate as KennyTM noted. – Claus Broch Aug 19 '10 at 12:11
0

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)
ankitjaininfo
  • 11,961
  • 7
  • 52
  • 75
  • I've been hearing a lot about using factories instead of overloading "new" recently... why is this? – xitrium Aug 19 '10 at 12:04
  • ''An access method to get the last instance (from the top of stack)'' ---- ??? Can you explain this more detailed? – IanH Aug 19 '10 at 12:11