Helpful Information
 
 
Category: C Programming
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.

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.


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];
}

Ah stupid me. Somehow I thought the CD instances in the array would be deleted after the CreateCDs() function exits...

Thanks for your help =)

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.

Oops, my bad... Nice catch!










privacy (GDPR)