Array of Object in C++

As we know array is a collection of similar data elements. We can also create array of object.

Que. WAP to create a array of object. initialize and display the content of array.

  OR  WAP  to create a class player and take a details from user name, age and print. Also use  array of object.

#include 

using namespace std;

class player {
        private:
                int age;
        char name[20];
        public:
                void input();

        void show();
};

void player::input() {
        cout << "enter name & age=";
        cin >> name >> age;
}
void player::show() {
        cout << "player name =" << name;
        cout << "\tage =" << age << endl;
}
int main() {
        player x[3]; // array of object        
        cout << "enter details";
        x[0].input();
        x[1].input();
        x[2].input();
        x[0].show();
        x[1].show();
        x[2].show();

}

Output

enter details                                                                                                                                                                enter name & age=  
Raj
23                                                                                                                                                                                  enter name & age = 
Sam 
22                                                                                                                                                                                    enter name & age= 
Adi
  23                                                                                                                                               
player name = Raj   age =23                                                                                                                                               player name =  Sam age =22                                                                                                                                               player name = Adi   age =23
 

Note: In the above program we have creates three object “player[3]”.

Categories C++