CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: no. of objects

  1. #1
    Join Date
    Oct 2001
    Posts
    6

    no. of objects

    can u tell me . Thanks
    Suppose you need to keep track of how many objects of a given class exist. What is the best way (if there is one) to do this?
    Choice 1
    Add a static member variable that gets incremented in each constructor and decremented in the destructor.
    Choice 2
    This cannot be accomplished since the creation of objects can be done dynamically via "new".
    Choice 3
    Add a register member variable that gets incremented in each constructor and decremented in each destructor.
    Choice 4
    Add an automatic local variable that gets incremented in each constructor and decremented in the destructor.
    Choice 5
    Add an automatic member variable that gets incremented in the default constructor and decremented in the destructor.

    Bye yours
    Manorama
    Email: [email protected]

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449
    The best answer is 1. However you must make sure that for every version of the object's constructor, the static member is incremented.

    Answer 2 is incorrect -- it doesn't matter how the object was created. The proper constructor is called, even if you created the object using "operator new".

    The others do not work for the obvious reasons. Non-static members are only valid for the particular instance. Once the object is destroyed, those members cease to exist.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Oct 2001
    Location
    Dublin, Eire
    Posts
    880
    Originally posted by Paul McKenzie

    The others do not work for the obvious reasons. Non-static members are only valid for the particular instance. Once the object is destroyed, those members cease to exist.
    And not only that. You cannot in one local instance know how many ither where created. Thus, you cannot set this local variable value to the number of instances.

    I agree that the first solution is the only one that is always working.

    Another solution for a very specific case, is if you create and delete all your instances always in the same "place" (your class is used only by one other class, that has only one instance). Then you can add a counter there, or add them in a list, the size of the list being the number of instances. But this is a very specific case.
    Elrond
    A chess genius is a human being who focuses vast, little-understood mental gifts and labors on an ultimately trivial human enterprise.
    -- George Steiner

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured