c++ - Dynamic Memory Allocation for Objects -


  #include <iostream>    class myclass    {       public:           myclass() {               itsage = 1;               itsweight = 5;           }            ~myclass() {}           int getage() const { return itsage; }           int getweight() const { return itsweight; }            void setage(int age) { itsage = age; }        private:           int itsage;           int itsweight;    };    int main()   {       myclass * myobject[50]; // define array of objects...define type object       int i;       myclass * objectpointer;       (i = 0; < 50; i++)       {           objectpointer = new myclass;           objectpointer->setage(2*i + 1);           myobject[i] = objectpointer;       }        (i = 0; < 50; i++)           std::cout << "#" << + 1 << ": " << myobject[i]->getage() << std::endl;        (i = 0; < 50; i++)       {           delete myobject[i];           myobject[i] = null;       } 

i wondering why objectpointer must inside loop, if take out , place right before loop, nonsensical results. appreciated, thanks...sorry terrible formatting.

 myobject[i] = objectpointer; 

it should inside loop because storing new reference in array of pointers. if outside loop, array of pointers point same reference. in such scenario, should careful while deallocation array of pointers point same memory location.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -