Arrays of Objects
Objectsare variables and have the same
capabilities and attributes as any other type of
variables. Therefore, it is perfectly acceptable for
objects to be arrayed
The syntax for declaring an array of objects is
exactly as that used to declare an array of any
other type of variable.
Further, arrays of objects are accessed just like
arrays of other types of variables.
2.
class Distance
{
private:
int feet;
floatinches;
public:
void getdist() //get length from user
{
cout << "n Enter feet: "; cin >> feet;
cout << " Enter inches: "; cin >> inches;
}
void showdist() const //display distance
{
cout << feet << "'-" << inches << '"';
}
};
3.
int main() {
Distancedist[100]; //array of distances
int n=0; //count the entries
char ans; //user response ('y' or 'n')
do { //get distances from user
cout << "Enter distance number " << n+1;
dist[n++].getdist(); //store distance in array
cout << "Enter another (y/n)?: ";
cin >> ans;
} while( ans != 'n' ); //quit if user types ‘n’
for(int j=0; j<n; j++) { //display all distances
cout << "nDistance number " << j+1 << " is ";
dist[j].showdist();
}
return 0;
}
Constructor (Single
Argument)
If theclass includes a constructor
with single argument, an array of
objects can be initialized in the
following way;
6.
Example 1
class samp{
int a;
public:
samp(int n);
int getA();
};
samp::samp(int n) {
a = n;
}
int samp::getA() {
return a;
}
7.
Example 1…
int main(){
samp ob[4] = {-1, 5, 6, 90};
for (int j=0; j<4; j++)
{
cout << ob[j].getA() << endl;
}
return 0;
}
8.
Arrays of Objectswith
Constructor
(Multiple Arguments)
A To invoke a constructor with
arguments, a list of initial values should
be used. To invoke a constructor with
more than one arguments, its name
must be given in the list of initial values.
If the class includes a constructor with
multiple arguments, an array of objects
can be initialized in the following way;
9.
Example 2
class samp{
int a, b;
public:
samp(int n, int m);
int getSum();
};
samp::samp(int n, int m) {
a = n;
b = m;
}
int samp::getSum() {
return a+b;
}
10.
Example 2…
int main(){
samp ob[4] = { samp(1, 2), samp(3, 4), samp(5,6), samp(7,8)};
for (int j=0; j<4; j++)
{
cout << ob[j].getSum() << endl;
}
return 0;
}