#1
  1. No Profile Picture
    Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2000
    Posts
    13
    Rep Power
    0

    Dynamic Size for a private member


    Hi,

    Let's say I have a class called "CDlibrary", and inside this class, I have a class called "CD" as a private member. An instance of CDlibrary can contain multiple CDs. I don't know how many CDs I have before I initialize the CDlibrary instance. How do I design the CDlibrary class so that different instances can contain different # of CDs?

    eg. If every library has 1 CD then:

    class CDlibrary {
    private:
    CD disc1;
    };

    Thanks for your help in advance.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    You could try declaring a pointer to an array of class CD. In the class constructor for CDLibrary, you can initialize the pointer to null. Then, when you know how many CDs you have, you can allocate the memory as needed. Also, in your destructor, you can check if you allocated memory to hold the CDs or not and destroy the array appropriately E.g.
    Code:
    class CDlibrary { 
      private: 
          CD *discs; 
          int nDiscs;
      public:
          CDLibrary();
          ~CDLibrary();
          void CreateCDs(int num);
    }; 
    
    CDLibrary::CDLibrary() {
        discs = NULL;
    }
    
    CDLibrary::~CDLibrary() {
       if (discs) {
            delete discs;
            discs = NULL;
       }
    }
    
    void CDLibrary::CreateCDs(int num) {
        nDiscs = discs;
        discs = new CD[num];
    }
  4. #3
  5. No Profile Picture
    Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2000
    Posts
    13
    Rep Power
    0
    Ah stupid me. Somehow I thought the CD instances in the array would be deleted after the CreateCDs() function exits...

    Thanks for your help =)
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Location
    Oxford, UK
    Posts
    28
    Rep Power
    0
    Um....

    When you delete an array, you MUST use

    delete [] discs;

    The reason is that delete discs will only delete the first element, so you will leave most of your allocated memory hanging.
  8. #5
  9. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    Oops, my bad... Nice catch!

IMN logo majestic logo threadwatch logo seochat tools logo