Tuesday, October 21, 2014

Create space for an array of objects using pointer

#include <iostream.h>

class array_object
{
     private:  int x;
     public:   void setdata(int i)
                    {
                         x = i;
                    }
                    int getdata()
                    {
                        return x;
                    }
};


int main()
{
   array_object *ob1;
   ob1=new array_object[4];  // using new operator allocate memory
  int i;

  for(i=0; i < 4; i++)
     ob1[i].setdata(i);

  for(i=0; i < 4; i++)
     cout << "ob1[" << i << "].getdata(): " << ob1[i].getdata() << "\n";

  return 0;
}

No comments:

Post a Comment