by Dinesh Thakur Category: Classes in C++

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


using namespace std;

const int size=5;

class student


int roll_no;

int marks[size];


void getdata ();

void tot_marks ();

} ;

void student :: getdata ()


cout<<"\nEnter 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;



The output of the program is


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

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles