OOP - Week 5, Lecture 3: This Pointer, Friend Functions and Classes
Setting Up a Student Takes Too Many Lines
A student with three subjects needs three grades. With what we know, this is how we set them:
Student a(1, 3);
a.setGrade(0, 90);
a.setGrade(1, 80);
a.setGrade(2, 70);
The a. is repeated on every line. It would be nicer to write all three calls in one statement:
a.setGrade(0, 90).setGrade(1, 80).setGrade(2, 70);
There is a second problem. We want a function printReport that prints everything about a student: the id, and every grade. It is not a member of Student, so it cannot read the private members id and grades.
This lecture solves both problems. The first needs the this pointer, and the second needs a friend function.
1. The this Pointer
When you call a member function, the function must know which object it works on. In a.setId(5), the function works on a. C++ does this with a hidden pointer named this, which every non-static member function receives. It holds the address of the object the function was called on.
Inside a member function, a name like id is short for this->id:
void Student::print() const {
cout << id; // the same as: cout << this->id;
}
You almost never need to write this->. The common exception is a parameter that has the same name as a data member. The parameter hides the member:
void Student::setId(int id) {
id = id; // the parameter is assigned to itself: the member does not change
}
Here id means the parameter on both sides, so the data member of the object is never set. Some compilers warn about this. this-> says which one you mean:
void Student::setId(int id) {
this->id = id; // this->id is the data member, id is the parameter
}
this also explains something from Week 4. A static member function is not called on an object, so it has no this. That is the reason it cannot use a non-static member by its name only: there is no object to take it from.
2. Returning *this: Chaining
this is a pointer, so *this is the object itself. If a member function ends with return *this;, it gives back the object it was called on. Then the next call can be made on the result:
Student& Student::setGrade(int index, double value) {
if (index >= 0 && index < numSubjects && value >= 0.0 && value <= 100.0)
grades[index] = value;
return *this; // give back the same object
}
Now the three calls can be one statement. Each call returns a, and the next call is made on it:
a.setGrade(0, 90).setGrade(1, 80).setGrade(2, 70);
This is the same as three separate statements, and it is called chaining.
The return type is Student&, a reference, so the function gives back the object itself, not a copy.
If the return type were
Studentwithout the&, every call would return a copy. The first call would changea, but the second call would change a temporary copy, andawould keep only the first change. Each call would also run the copy constructor, which is slow when the class owns an array.
Only functions that return *this can be in the middle of a chain. A function that returns something else, like average(), can only be the last call.
3. Friend Functions
A normal function that is not a member of the class cannot use its private members:
void printReport(const Student& s) {
cout << s.id; // error: 'id' is a private member of 'Student'
}
We could add a getter for every member, but sometimes we want one function to see inside the class. The class can give this permission to a function by declaring it a friend:
class Student {
private:
int id;
int numSubjects;
double* grades;
public:
friend void printReport(const Student& s); // printReport may use the private members
};
The function itself is written outside the class, and now it can read the private members:
void printReport(const Student& s) {
cout << "report: student " << s.id << ", " << s.numSubjects << " subjects" << endl;
for (int k = 0; k < s.numSubjects; k++)
cout << " subject " << k + 1 << ": " << s.grades[k] << endl;
}
A friend function is not a member:
- Its definition has no
Student::before the name, and it has nothis. - You call it like a normal function, without a dot:
printReport(a);, nota.printReport();. - It needs an object to work on, so it receives the student as a parameter.
- The class decides who its friends are. A function cannot make itself a friend.
- It does not matter if the
friendline is in thepublicor theprivatepart of the class. - Also write a normal prototype after the class in the header, so any file that includes the header can call the function.
A friend can read and change the private members, so it breaks the protection that
privategives. Do not use it often. Use it only when a function really needs to see inside the class, and prefer getters when they are enough.
4. Friend Classes
A friend function gives access to one function. Sometimes a whole class needs the access. For example, a TA (teaching assistant) curves and prints the grades of students, and both jobs need the private members of Student.
Instead of making every function of TA a friend, Student can make the class TA its friend:
class Student {
private:
int id;
double grade;
public:
Student(int i, double g) : id(i), grade(g) {}
friend class TA; // all the functions of TA may use the private members
};
class TA {
public:
void curve(Student& s, double bonus) {
s.grade += bonus;
}
void print(const Student& s) const {
cout << "student " << s.id << ": " << s.grade << endl;
}
};
int main() {
Student s(7, 80);
TA t;
t.curve(s, 5);
t.print(s);
}
The output is:
student 7: 85
curve and print use s.grade and s.id even though they are private, because TA is a friend of Student.
- The
friend class TA;line is written insideStudent. The class that gives the permission chooses its friends. - Every function of
TAgets the access. TAstill needs a student to work on, so the student is a parameter.- A friend goes one way.
TAcan use the private members ofStudent, butStudentcannot use the private members ofTA. For that,TAwould also needfriend class Student;.
A friend class can read and change all the private members, so use it only when two classes really work as a pair.
5. Friend Member Functions
A friend class gives the access to all the functions of TA. If only one function of TA needs it, Student can make just that function a friend. The line has the class name and the function name: TA::curve.
class Student; // Student exists, it is written below
class TA {
public:
void curve(Student& s, double bonus);
void print(const Student& s) const;
};
class Student {
private:
int id;
double grade;
public:
Student(int i, double g) : id(i), grade(g) {}
friend void TA::curve(Student& s, double bonus); // only curve
};
void TA::curve(Student& s, double bonus) {
s.grade += bonus; // allowed: curve is a friend
}
void TA::print(const Student& s) const {
cout << s.id; // error: 'id' is a private member of 'Student'
}
Only curve can use the private members. print is also a function of TA, but it is not a friend, so it cannot.
There are two details about the order:
TAis written beforeStudent, so the compiler knows the functionTA::curvewhen it reads the friend line.- The bodies of
curveandprintare written afterStudent, because they usegradeandid, and the compiler must know them first.
6. Putting It Together
This is the Student of Lecture 2, in the same three files. setId, setGrade and addSubject now return Student&, so they can be chained, and printReport is a friend. Click Changes since Lecture 2 to see exactly which lines are new. main sets three grades in one chain, prints a report, then adds a subject and changes the id in one chain.
#ifndef STUDENT_H
#define STUDENT_H
class Student {
private:
int id;
int numSubjects; // how many subjects the student takes
double* grades; // one grade for each subject, on the heap
public:
Student(int i, int n); // n subjects, all grades 0 at first
Student(const Student& other); // copy constructor: a deep copy
~Student(); // gives the array back
Student& setId(int id); // returns the object, so calls can be chained
Student& setGrade(int index, double value);
Student& addSubject(double grade); // the student takes one more subject
double average() const;
void print() const;
friend void printReport(const Student& s); // not a member: a friend of Student
};
void printReport(const Student& s); // the prototype for the callers
#endif#include <iostream>
#include "Student.h"
using namespace std;
Student::Student(int i, int n) : id(0), numSubjects(n), grades(new double[n]) {
setId(i);
for (int k = 0; k < numSubjects; k++) // new does not clear the values
grades[k] = 0.0;
cout << "constructor " << id << endl;
}
Student::Student(const Student& other)
: id(other.id), numSubjects(other.numSubjects), grades(new double[other.numSubjects]) { // a new array
for (int k = 0; k < numSubjects; k++)
grades[k] = other.grades[k]; // copy the values, not the pointer
cout << "copy constructor " << id << endl;
}
Student::~Student() {
delete[] grades; // release the array of this student
cout << "destructor " << id << endl;
}
Student& Student::setId(int id) {
if (id > 0)
this->id = id; // this->id is the member, id is the parameter
return *this; // the object itself, not a copy
}
Student& Student::setGrade(int index, double value) {
if (index >= 0 && index < numSubjects && value >= 0.0 && value <= 100.0)
grades[index] = value;
return *this;
}
Student& Student::addSubject(double grade) {
double* bigger = new double[numSubjects + 1]; // 1. a new array, one element larger
for (int k = 0; k < numSubjects; k++)
bigger[k] = grades[k]; // 2. copy the old grades
bigger[numSubjects] = 0.0;
delete[] grades; // 3. release the old array
grades = bigger; // 4. grades points to the new array
numSubjects++;
setGrade(numSubjects - 1, grade); // 5. the grade of the new subject
return *this;
}
double Student::average() const {
if (numSubjects == 0)
return 0.0;
double sum = 0.0;
for (int k = 0; k < numSubjects; k++)
sum += grades[k];
return sum / numSubjects;
}
void Student::print() const {
cout << "id " << id << ":";
for (int k = 0; k < numSubjects; k++)
cout << " " << grades[k];
cout << ", average " << average() << endl;
}
void printReport(const Student& s) { // not a member: no Student::, no this
cout << "report: student " << s.id << ", " << s.numSubjects << " subjects" << endl;
for (int k = 0; k < s.numSubjects; k++)
cout << " subject " << k + 1 << ": " << s.grades[k] << endl;
}#include <iostream>
#include "Student.h"
using namespace std;
int main() {
Student a(1, 3); // 3 subjects
a.setGrade(0, 90).setGrade(1, 80).setGrade(2, 70); // three calls, one statement
printReport(a); // a friend: called like a normal function
a.addSubject(85).setId(5); // two different functions in one chain
printReport(a); // the report shows both changes
return 0;
} // a is destroyed here#ifndef STUDENT_H
#define STUDENT_H
class Student {
private:
int id;
int numSubjects; // how many subjects the student takes
double* grades; // one grade for each subject, on the heap
public:
Student(int i, int n); // n subjects, all grades 0 at first
Student(const Student& other); // copy constructor: a deep copy
~Student(); // gives the array back
void setId(int i);
void setGrade(int index, double value);
void addSubject(double grade); // the student takes one more subject
double average() const;
void print() const;
};
#endif
#include <iostream>
#include "Student.h"
using namespace std;
Student::Student(int i, int n) : id(0), numSubjects(n), grades(new double[n]) {
setId(i);
for (int k = 0; k < numSubjects; k++) // new does not clear the values
grades[k] = 0.0;
cout << "constructor " << id << endl;
}
Student::Student(const Student& other)
: id(other.id), numSubjects(other.numSubjects), grades(new double[other.numSubjects]) { // a new array
for (int k = 0; k < numSubjects; k++)
grades[k] = other.grades[k]; // copy the values, not the pointer
cout << "copy constructor " << id << endl;
}
Student::~Student() {
delete[] grades; // release the array of this student
cout << "destructor " << id << endl;
}
void Student::setId(int i) {
if (i > 0)
id = i;
}
void Student::setGrade(int index, double value) {
if (index >= 0 && index < numSubjects && value >= 0.0 && value <= 100.0)
grades[index] = value;
}
void Student::addSubject(double grade) {
double* bigger = new double[numSubjects + 1]; // 1. a new array, one element larger
for (int k = 0; k < numSubjects; k++)
bigger[k] = grades[k]; // 2. copy the old grades
bigger[numSubjects] = 0.0;
delete[] grades; // 3. release the old array
grades = bigger; // 4. grades points to the new array
numSubjects++;
setGrade(numSubjects - 1, grade); // 5. the grade of the new subject
}
double Student::average() const {
if (numSubjects == 0)
return 0.0;
double sum = 0.0;
for (int k = 0; k < numSubjects; k++)
sum += grades[k];
return sum / numSubjects;
}
void Student::print() const {
cout << "id " << id << ":";
for (int k = 0; k < numSubjects; k++)
cout << " " << grades[k];
cout << ", average " << average() << endl;
}
#include <iostream>
#include "Student.h"
using namespace std;
int main() {
Student a(1, 3); // 3 subjects, so 3 grades
a.setGrade(0, 90);
a.setGrade(1, 80);
a.setGrade(2, 70);
a.print(); // the original
Student b = a; // the copy constructor: b gets its own array
b.setGrade(0, 50); // change only the copy
b.print(); // only b changed
a.print(); // a is not changed
a.addSubject(85); // a takes a 4th subject: its array is resized
a.print(); // four grades now
b.print(); // b still has three: it has its own array
Student* p = new Student(2, 2); // on the heap, with 2 subjects
p->setGrade(0, 95);
p->setGrade(1, 85);
p->print();
delete p; // the destructor releases its array
p = nullptr;
return 0;
} // b and a are destroyed here
Click each line of output to see what caused it.