Home | | Computer Science 11th std | C++: Array of objects

Example Programs in C++ - C++: Array of objects | 11th Computer Science : Chapter 14 : Classes and objects

Chapter: 11th Computer Science : Chapter 14 : Classes and objects

C++: Array of objects

An array which contains the class type of element is called array of objects.

Array of objects

 

An array which contains the class type of element is called array of objects. It is declared and defined in the same way as any other type of array.

 

Illustration 14.5 Array of objects

gets () can accept a string with space which is not possible by cin.

#include<iostream> 

#include<stdio.h> 

using namespace std;

class stock 

      int itemno; 

      char itemname[10];  // array as member variable

      float price;

      public: 

      void getdata()

      {

      cin>>itemno>>price;

      gets(itemname);

}

void putdata()

{

      cout<<’\n’<<itemno<<’\t’<<itemname<<’\n’<<price;

}

};

int main()

{

stock s[10];

int i;

cout<<”Enter the details\n”;

      for( i=0;i<10;i++)

           s[i].getdata();

cout<<”\n Item Details\n”;

cout<<”\nITEM NO \t ITEM NAME\t PRICE”<<endl;

      for( i=0;i<10;i++)

           s[i].putdata();

 return 0;

}

Output

Item Details

ITEM NOITEM NAME          PRICE

101     APSARA PENCIL       Price10.5

102     FABER CASTELL PENCIL  Price12.0001

103     NATARAJ PENCIL     Price9.75

201     PILOT V7 PEN            Price50

201     CELLO BUTTERFLOW        Price10

202     PARKER PEN             Price450

202     PILOT FOUNTAIN PEN       Price600

301     APSARA ERASER      Price5

302     FABER CASTELL ERASER Price15.0001

303     NATARAJ ERASER   Price3

                            


The above program accepts the details of 10 items and display the same.In the program if you observe there are 10 objects created and are accessing the member function through for loop. To invoke putdata() for a particular object for example for object 6 we will give

s[5].putdata( ); //array index start with 0. So index 5 refers to 6th object

 

Tags : Example Programs in C++ , 11th Computer Science : Chapter 14 : Classes and objects
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 14 : Classes and objects : C++: Array of objects | Example Programs in C++

Related Topics

11th Computer Science : Chapter 14 : Classes and objects


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.