CPP Array of Objects in c++

Array of Objects in c++

  • Like array of other user-defined data types, an array of type class can also be created.
  • The array of type class contains the objects of the class as its individual elements.
  • Thus, an array of a class type is also known as an array of objects.
  • An array of objects is declared in the same way as an array of any built-in data type.


class_name array_name [size] ;


#include <iostream> 
class MyClass { 
  int x; 
  void setX(int i) { x = i; } 
  int getX() { return x; } 
void main() 
  MyClass obs[4]; 
  int i; 
  for(i=0; i < 4; i++) 
  for(i=0; i < 4; i++) 
    cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n"; 


obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3


Share This Page on:

Ask Question