Anda di halaman 1dari 11

ment of Computer Science & Engi

Air University
Object Oriented
Programming
Week # 9
Array Of Objects
Lecture # 9
By: Saqib Rasheed
Arrays of Objects
Objects are 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.
class Distance
{
private:
int feet;
float inches;
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 << '\"';
}
};
int main() {
Distance dist[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;
}
Arrays of Objects
Arrays of Objects with
Constructor (Single Argument)
If the class includes a constructor with
single argument, an array of objects
can be initialized in the following way;
Example 1
class samp {
int a;
public:
samp(int n);
int getA();
};

samp::samp(int n) {
a = n;
}
int samp::getA() {
return a;
}
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;
}
Arrays of Objects with 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;
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;
}
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;
}

Anda mungkin juga menyukai