Code:
#include <iostream>
using namespace std;
class Student {
int no;
double gpa;
public:
Student();
Student(double g);
Student(const Student&);
void operator++();
Student& operator=(const Student& s);
friend Student operator+(const Student& s, double d);
friend ostream& operator<<(ostream& os, const Student& s);
~Student();
};
Student::Student() {
cout << '#';
no = 0;
gpa = 0.0;
}
Student::Student(double g) {
cout << '@';
no = 1;
gpa = g;
}
Student::Student(const Student& s) {
cout << '*';
*this = s;
}
void Student::operator++() {
no++;
}
Student& Student::operator=(const Student& s) {
cout << '=';
no = s.no;
gpa = s.gpa;
return *this;
}
Student::~Student() {
cout << '~' << *this << endl;
}
Student operator+(const Student& s, double d) {
cout << '+';
Student result = s;
cout << '+';
result.gpa = (result.gpa * result.no + d);
result.no++;
result.gpa /= result.no;
return result;
}
ostream& operator<<(ostream& os, const Student& s) {
return os << s.no << '-' << s.gpa;
}
int main() {
Student s[2];
cout << endl;
s[0] = 2.0; // THIS ONE CALLS THE Student::Student(double g).
s[1] = 3.0; IT Also calls Student& Student::operator(const Student& s) and the destructor which I dont get it.
s[0] = s[0] + 2.0;
++s[0];
cout << s[0] << endl;
cout << s[1] << endl;
return 0;
}
Output:
##
@=~1-2
@=~1-3
+*=+*=~2-2
=~2-2
3-2
1-3
~1-3
~3-2
Question:
I dont get why I got @=~1-2
and @=~1-3.
The destructor was called but I dont know how.