Saturday, 10 September 2016

ARRAY OF OBJECTS


When you define a class, you can also define the array of objects of Class type. Declared after the class definition is over and is defined like the other arrays are defined.


Example: 

class student
{
private: 
             int roll_no;
            

public:
             void getdata(int roll)
             {
               roll_no= roll;
         
             }
            
            void show()
            {
              cout<<"Roll No.: "<<roll_no;
            
            }
};

student s[5];    //Array of Objects of "student" Class Type which contain the information of 5 Students

void main()
{
clrscr();
int rollno;


for(int i=0; i<5;i++)
  {
    cout<<"Enter the Details of Student "<<i+1<<"\n";
    cin>>rollno;   
    
    s[i].getdata(rollno);
  }

for(int j=0;j<5;j++)
 {
   cout<<"\nStudent "<<j+1<<"\n";
   s[j].show();
 }
getch();
}


Now let's say, to invoke function 'show' the 3rd Object of class student, we will write: 
s[2].show();  // As array starts from 0

No comments:

Post a Comment