Arrays can be declared as the members of a class. The arrays can be declared as private, public or protected members of the class.
To understand the concept of arrays as members of a class, consider this example.
Example: A program to demonstrate the concept of arrays as class members
The output of the program is
#include<iostream> using namespace std; const int size=5; class student { int roll_no; int marks[size]; public: void getdata (); void tot_marks (); } ; void student :: getdata () { cout<<"\nEnter roll no: "; cin>>roll_no; for(int i=0; i<size; i++) { cout<<"Enter marks in subject"<<(i+1)<<": "; cin>>marks[i] ; } void student :: tot_marks() //calculating total marks { int total=0; for(int i=0; i<size; i++) total+ = marks[i]; cout<<"\n\nTotal marks "<<total; } int main() { student stu; stu.getdata() ; stu.tot_marks() ; return 0; }
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
In this example, an array marks is declared as a private member of the class student for storing a student’s marks in five subjects. The member function tot_marks () calculates the total marks of all the subjects and displays the value.
Similar to other data members of a class, the memory space for an array is allocated when an object of the class is declared. In addition, different objects of the class have their own copy of the array. Note that the elements of the array occupy contiguous memory locations along with other data members of the object. For instance, when an object stu of the class student is declared, the memory space is allocated for both rollno and marks