0

I have to write a C++ code must also perform sorting of multiple objects of the following class:

class student
{
    int roll, m[5], total;
    bool pass;
    char name[30];
public:
    void read();
    void result();
    void print();
    void operator=(student&);
    friend void sort(student, int);
};
void sort(student var[], int size)
{
    int s,t;
    for (s = 0; s<size; s++)
    for (t = 0; t<size; t++)
    {
        if (var[s].total<var[t].total)      //---------line 22----------
    {   
            student x;
            x = var[s];
            var[s] = var[t];
            var[t] = x;
        }
    }
}

void student::operator=(student &x)
{
roll=x.roll;
strcpy_s(name,x.name);
for(int v=0;v<5;v++)
m[v]=x.m[v];
total=x.total;
pass=x.pass;
}
void main()
{
student s[4];
int ni, n;
cout<<"Enter number of student records: ";
cin >> n;
for (ni = 0; ni<n; ni++)
{
    s[ni].read();
    s[ni].result();

}
sort(s, n);
cout<<endl<<"List sorted based on total: "<<endl;
for (ni = 0; ni<n; ni++)
{
    s[ni].print();
}
}

I use Visual C++ 2008. When I compiled this code it displays two errors:

Error1 error C2248:'student::total': cannot access private member declared in class 'student'


Error2 error C2248:'student::total': cannot access private member declared in class 'student'

These errors are shown at same line 22 that is while accessing total. Although sort() is a friend function I get this accessibility error.

I noted that if total declared public, there is no error. but as per class specification it has to be private. Please help me.

Abhilash
  • 2,026
  • 17
  • 21

1 Answers1

1

The correct friend function declaration will look like

friend void sort(student[], int);

There is a difference between the function declaration and the function definition in your code. They do not coincide Take into account that the correct declaration of the copy assignment operator will look like

student & operator =( const student & );     

Also function main shall have return type int

int main()
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Please tell me what does const do? – Abhilash Oct 18 '14 at 18:45
  • @Abhilash Iyer It means that the object in the right side of the assignment operator will not be changed. It is considered as an immutable object. – Vlad from Moscow Oct 18 '14 at 18:47
  • Ok. There is more code to be added. Sorting is to be done for student object and all changes give me the correct result. But I have to sort generic data as part of this code. It may be int,float,string (and of course student object). If templates are used, how to specify code for differing data types? – Abhilash Oct 18 '14 at 18:52
  • @Abhilash Iyer You should write the sort function such a way that it would accept a binary predicate. Take into account that there is already standard function std::sort declared in header – Vlad from Moscow Oct 18 '14 at 18:58