user2093601 user2093601 - 1 month ago 6
C++ Question

Access member function from array of objects

I'm trying to dynamically create an array of objects and then use the member functions of the objects in the array. I've tried a couple of combinations but crash my program when I try to invoke the display member on objects in the array.

Something * pSomethings[12] = { NULL }; //pointer to array of 12 Somethings

to load the array I use:
Something * pSomething; //create a temp pointer of Something
pSomething = pSomethings[0]; //assign temp pointer to first item in array
pSomething = new Widget(size, weight);//pSomthings[0] should be a new widget
cout << pSomething->getSize(); //seeing if data member was set (shows correct)
cout << pSomething->getWeight(); //seeing if data member was set (shows correct)

when I try to invoke the following my program breaks:
Something::display(){
Something * pSomething; //create another local temp pointer
pSomething = psomethings[0];//assign temp pointer to initialized pSomthing above
cout << pSomething->getSize(); // <---- breaks if run in main.
}


I'm new to c++ and pointers in general so I could be making a very simple mistake but I simply don't understand why getSize() displays correctly in the first function but in display() I create everything the same (temp pointer, assign to same index etc.) and I get an error.

Answer

Take a look at the comments here:

pSomething = pSomethings[0]; //assign temp pointer to first item in array
pSomething = new Widget(size, weight);//pSomthings[0] should be a new widget

The last comment is incorrect as you assign the value returned by new to pSomething, not to pSomethings[0].

You should have written:

pSomethings[0] = new Widget(size, weight); //pSomthings[0] should be a new widget

Now the code and the comment are correct.

Comments