Hey everyone. I'm new around here. I need to create an array of class pointers, and I'm stuck.
I have currently tried the following:
1 2 3 4
dispenserType *p; // create class pointer object
p = new dispenserType[4]; // make class pointer object into an array
dispenserType one(100, 50);
p[0] = &one;
I have tried this a few different ways, but I see no way to make this happen (I get an error every time I try to assign the objects). How can I do an array of pointer-class objects?
p[0] = &one; is a memory leak. you already created a dynamic array of 4 objects. What is the specific error? Please provide a more complete example, give us the error message, and tell us which line of code is resulting in the error.
The assignment that you showed actually looked correct in terms of the assignment so what you are saying just doesn't make sense.
Did you see this tutorial? I believe that the new statement already default constructed 4 dispensorType objects. Therefore assigning to p[0] as you had done is not only a memory leak but also dangerous since it appears that you overwrite the pointer to dynamic memory with a pointer to stack memory. http://www.cplusplus.com/doc/tutorial/dynamic/
The assignment that you showed actually looked correct in terms of the assignment
Correct me if I'm wrong, but p points to an array of objects of type dispenserType rather than dispenserType* (as the title of this thread would suggest), which means p[0] is not a pointer.