how to use "friend"

Hello, I am having an issue with my program, but I don't know what I am doing wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>
using namespace std;

class Teacher {
private:
	string name;
public:
	void setGrade(double g) {Student::grade = g;}
	double getGrade() const {return Student::grade;}
};

class Student {
private:
	double grade;
public:
	friend void Teacher::setGrade(double);
	friend double getGrade();
};


main.cpp:9:27: error: use of undeclared identifier 'Student'
        void setGrade(double g) {Student::grade = g;}
                                 ^
main.cpp:10:34: error: use of undeclared identifier 'Student'
        double getGrade() const {return Student::grade;}
                                        ^
2 errors generated.


Help is appreciated. Thanks!
When read from top to bottom, the compiler first comes across a identifer "Student" on line 9. At this point, it has no idea what a Student is.
You can circumvent this by adding a declaration of the student class before your Teacher class.

In this case you may need to separate implementation from interface for this or else you might get compiler errors about incomplete type usage.

Another problem is that Student::grade refers to no object. It's simply a data member of the Student class.
You need to pass in an actual Student object into your function in order to mutate that.
Something like
1
2
3
setGrade(Student& student, double g) {
    student.grade = g;
}

Same error applies to the getGrade().

I modified your stuff a little, this should work fine. Notice how the functions are declared outside of their class definitions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Student; // class forward declaration
class Teacher {
private:
	string name;
public:
	void setGrade(Student& student, double g);
};

class Student {
private:
	double grade;
public:
	friend void Teacher::setGrade(Student& student, double g);
};

void Teacher::setGrade(Student& student, double g)
{
    student.grade = g;
}
Last edited on
Oh I think I understand, you could only something similar to what I tried to do if it were working with a static data member, is that correct?
Topic archived. No new replies allowed.