Re: restrict the creation of an object

From: gtSasha (gdalevich_at_hotmail.com)
Date: 03/26/04


Date: 25 Mar 2004 19:49:40 -0800


"greymatter" <greymatter@nospam.com> wrote in message news:<d20eec8612d022fe66d9ec815c5d079f@news.teranews.com>...
> Hi, would anyone know how to restrict the creation of an object. Lets say
> that code specification required a maximum of 10 objects created at any one
> time. I know that a static variable in a class could keep count of the
> number of objects of any one kind created. But how can i tell the code not
> to create more than 10 objects. So for example if my main() tried to create
> an 11th object, the code would return with "Sorry, not possible to create
> object". I dont understand how to do this.
>
> Any help appreciated!
> thanks
> grey

There are several ways to do this. Most are described in the famous
"More Effective C++" book by Scott Meyers. If you can get your hands
on this book just look at "Item 26 - limiting object instantiations".

The simplest method is to keep a global counter for the number of
objects in the program and throw an exception out of constructor if
counter exceeds the specified limit. Another way, if you can't use
exceptions, is to use a factory pattern - make a different object or
function responcible for creating objects and keep a counter.

Good luck.



Relevant Pages

  • Re: Returning an object
    ... each method could throw an exception due to IO errors so I was ... The calling class currently calls a single method in the creation ... If an exception is thrown the object will not be built and the calling ... Not only clunky but unnecessary. ...
    (comp.lang.java.programmer)
  • Re: Returning an object
    ... each method could throw an exception due to IO errors so I was ... The calling class currently calls a single method in the creation ... If an exception is thrown the object will not be built and the calling ... Does the caller know about ...
    (comp.lang.java.programmer)
  • Returning an object
    ... each method could throw an exception due to IO errors so I was ... The calling class currently calls a single method in the creation ... If an exception is thrown the object will not be built and the calling ... Any advice would be appreciated. ...
    (comp.lang.java.programmer)
  • restrict the creation of an object
    ... would anyone know how to restrict the creation of an object. ... I dont understand how to do this. ...
    (comp.lang.cpp)
  • Restricting the creation of sites using templates
    ... We are creating site definitions and one of the requirements we have is ... to restrict the available type of sites for creation for a certain ... template. ...
    (microsoft.public.sharepoint.portalserver.development)

Loading