Reputation: 145
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;
}
Upvotes: 0
Views: 2149
Reputation: 890
As has been pointed out, Student[5].print(Student, N );
invokes undefined behavior as there is no Student[5]
. However, your implementation of print
doesn't actually use the object it is invoked on, so this is probably why this works in practice.
To give your program a somewhat reasonable design while keeping as close to the assignment as possible, you can declare the functions static
:
static void print(StudentRec Student[], int N );
This means that, while the functions are declared inside the class and have access to private members of objects of the class, they don't rely on any concrete object to be invoked. You can then use them like this:
StudentRec::print(Student, N);
On a side note, your implementation of print
doesn't actually use the parameter N
.
Upvotes: 1