Hello to all that read
I am self learning C++ from a text book:
A Question in the textbook asks me to make a function a friend of a class and therefore the friend function can have access to all of the classes members; which is fine I can do this.
Problem is that the question then goes on to ask that the friend function can only read the class members (private members) but NOT write to them!
**Please note: I have looked at similar question/answers on ‘stackoverflow’ – but I could not find the relevant and simple straight forward answer that I am after.
Here is some relevant code that I have, any help would be appreciated:
Many thanks in advance
#include <iostream>
#include <cstdio>
using namespace std;
class classroom{
private:
char name[25];
int student_id;
float grades[10];
float average;
int num_tests;
float letter_grade;
static int last_student_id;
public:
void enter_name_id(void);
void enter_grade(void);
void average_grades(void);
void letter_grades(void);
void output_name_id_grade(void);
void last_id(void);
classroom();
friend void readers(classroom&);
};
int classroom::last_student_id=1;
void readers(classroom& lee){
cout<<"\n number tests: "<<lee.num_tests;//friend function is reading class member -This is O.K!
lee.num_tests=15;//friend function is writing to class member - We don't want this to be allowed
cout<<"\n number tests: "<<lee.num_tests;//Used to test that class members are NOT accessed!
}
and in the main program we have:
int main()
{
classroom students[10];
readers(students[0]);
//and so on...
Once you declare a function as friend function, the access specifier rules are off, but you can prevent writing to members by passing in a const object to the friend function.
Note that
access specifiersandconstness are two different attributes, do not mix them.Note that your friend function can still try to modify the object by casting away the
constnessof the object by usingconst_castbut that would result in Undefined Behavior as per the Standard.