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.

Syntax:

class_name array_name [size] ;

Example:

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

Output:

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

 



Share This Page to Download:

Share to Download

Share This Page on:


Ask Question

Classes and Objects