Question : Declare a class named ‘StudentRec’ with three private members: ‘enrolNo’ of type int, ‘CGPA’ of type float and ‘branch’ of type string. Declare an array of objects named ‘Student’ of size 5 of class ‘StudentRec’. Write public member functions: (i) void sort (StudentRec Student[], int N ) to sort the data in ascending order with respect to ‘CGPA’ and (ii) void print (StudentRec Student[], int N ) to display the sorted and unsorted students’ records. Write main to test these member functions.
Doubt : The sorting part I will do later. My doubt is if in the below code(2nd last line ) Student[5].print(Student, N ); is correct way to call the function print? How else can this function be called via array of objects Also Student[0].print(Student, N ) gives correct output. Why ?
#include<iostream>
#include<cstring>
using namespace std;
class StudentRec
{
private:
int enrolNo;
float CGPA;
string branch;
public:
void assign()
{
cin>>enrolNo>>CGPA>>branch;
}
void sort (StudentRec Student[], int N );
void print(StudentRec Student[], int N )
{
int i;
for(i=0; i<5; i++)
{
cout<<"Student"<<" "<<i<<" " ;
cout<<Student[i].enrolNo<<" "<<Student[i].CGPA<<" "<<Student[i].branch<<endl;
}
}
};
int main()
{
StudentRec Student[5];
int i,N=5;
for(i=0; i<5; i++)
Student[i].assign();
Student[5].print(Student, N );
return 0;
}
Student[5].print(Student, N );invokes undefined behavior as your array only has a size of 5 (meaning the last valid index is 4)Student[5]. Has your course explained how basic array indexing works yet?sortandprintnon-staticmember functions? They don't rely on the instanceStudent[0].print ...but your teacher dosen't know anything about programming and C++-