array of object in c++

Arrays of the object:

In c++, an array of the object is possible. Let’s see one example.

#include<iostream>
Using namespace std;
Class display
{
Int i;
Public:
Void set(int j)
{
i=j; //Constructor
}
Void get()
{

Return i;
}

};

Int main()
{
Display ob[3];
Int i;
For(i=0;i<3;i++)
{
Ob[i].set(i+1);
}
For(i=0;i<3;i++)
{
Cout<<ob[i].get()<<”t”;
}
Return 0
}

Output

1  2  3

If a class defines a parameterized constructor, we initialize each object in an array by specifying an initialization list. The exact form of initialization will be decided by the number of parameters required by the object constructor.

Object initialization:

example

#include<iostream>
Using namespace std;
Class show
{
Public:
Set(int j){ i=j;  }  // constructor
Get() {   return i ;  }
};
Int main()
{
Show ob[ 3 ] = { 1,2,3 };    // initializers
Int i;
For(i=0; i<3; i++)
Cout<<ob[i].get()<<”n”;
Return 0;
}

Recommended Posts:

0 thoughts on “array of object in c++”

Leave a Comment