Using array of pointers to object in C++ -
i need save objects pointers in dynamic array have problem. code, there 3 classes , need have array (arrayoftwo) of poiters class 2 work further class 3 , on. have 2 problems. 1 cant figure out how dynamically allocate space arrayoftwo (which need dynamically resize number of stored pointers) , second problem how store pointers objects without destroying object itself. here code:
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; class 1 { public: bool addtwo(int a); private: void getspace(void); class 2 { public: int a; private: class 3 { /*...*/ }; 3 arrayofthree[]; }; int freeindex; int allocated; 2 *arrayoftwo[]; }; void one::getspace(void){ // how allocate space array of pointers ? arrayoftwo=new *two[100]; allocated=100; } bool one::addtwo(int a){ 2 temp; temp.a=a; getspace(); arrayoftwo[freeindex]=&temp; freeindex++; return true; //after leaving method, object temp still exist or pointer stored in array pointing on nothing ? } int main() { bool status; 1 x; status = x . addtwo(100); return 0; }
thank help.
edit: cant use vector or other advanced containers
temp
not exist after leaving addtwo
; pointer store invalid @ point. instead of storing object local variable, allocate on heap new:
two* temp = new two();
to allocate array of pointers:
two** arrayoftwo; // declare // ... arrayoftwo = new two*[100];
and getspace
should either passed a
(from addtwo
) or a
should stored member variable allocated
, getspace
should access there. otherwise it's assuming 100
.
Comments
Post a Comment