Thread: Static member of a class

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    87

    Static member of a class

    Hello everyone.

    I have a class but I want to create a static member of the class, so the objects can exchange data throught it. The member must be a dinamic char*, so I can pass strings through it, but the problem is how to 'delete' the dinamic memory, which I have alocated when there are no more objects?

    The only one sollution that I could think out was to have another one static variable, which counts the instances of the class and when the counter reaches 0, then I delete the memory in the destructor of the class.

    I wonder is any other way to manage static variables? And is there any way to do it in the end of the program no matter if there are 'live' objects?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    A string would be better because it would clean itself up... or perhaps you could use a smart pointer. Alternately, to do it with a basic character pointer as you are attempting, you would also need a static counter data member that would be set to 0 initially and then incremented each time a constructor was called and also decremented every time the destructor was called. If, when in the destructor after you've just decremented this value, you check the value and it is 0 then you know that there are no more instances of this object so you can then delete the memory at that point.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Sep 2003
    Posts
    87
    Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do i do this? (static structure inside class)
    By 39ster in forum C++ Programming
    Replies: 4
    Last Post: 11-17-2008, 03:14 AM
  2. Replies: 25
    Last Post: 10-29-2007, 04:08 PM
  3. Static variables and functions problem in a class
    By earth_angel in forum C++ Programming
    Replies: 16
    Last Post: 09-15-2005, 12:08 PM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  5. Replies: 3
    Last Post: 10-10-2002, 07:34 AM