user2249816
user2249816

Reputation: 9

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 the type as the object
      int i;
      MyClass * objectPointer;
      for (i = 0; i < 50; i++)
      {
          objectPointer = new MyClass;
          objectPointer->SetAge(2*i + 1);
          myObject[i] = objectPointer;
      }

      for (i = 0; i < 50; i++)
          std::cout << "#" << i + 1 << ": " << myObject[i]->GetAge() << std::endl;

      for (i = 0; i < 50; i++)
      {
          delete myObject[i];
          myObject[i] = NULL;
      }

I am wondering why the objectPointer must be inside the for loop, if I take it out and place it right before the for loop, I get nonsensical results. Help would be appreciated, thanks...sorry for the terrible formatting.

Upvotes: 0

Views: 56

Answers (1)

Mahesh
Mahesh

Reputation: 34655

 myObject[i] = objectPointer;

It should be inside the loop because you are storing a new reference in the array of the pointers. If it is outside the loop, then all the array of pointers point to the same reference. In such scenario, you should be careful while deallocation as all the array of pointers point to the same memory location.

Upvotes: 2

Related Questions