Reputation: 702
When the following code is compiled with C++11, it behaves as expected.
class Student;
class University
{
vector <Student*> students;
public:
University();
void print();
};
class Student
{
string name;
public:
Student(string nom) : name(nom) {}
friend ostream& operator << (ostream& out, Student* S)
{
return out << S -> name;
}
};
University::University()
{
for (string name: {"Alice", "Bob"})
students.push_back(new Student(name));
}
void University::print() { for (auto s: students) cout << s << '\n'; }
int main()
{
University uni;
uni.print();
}
The printout is
Alice
Bob
However, when the print() function is implemented inside its class declaration like this:
class University
{
vector <Student*> students;
public:
University();
void print() { for (auto s: students) cout << s << '\n'; }
};
The printout becomes
0x20055ff0
0x20056028
Question: Why does the print()
function behave like this even though Student
has been declared in the very first line?
Solution: Declare all classes before implementing any of their member functions. So long as print()
and operator <<
are both implemented after their classes' declaration, print()
will work correctly even if it's implemented before operator <<
Upvotes: 1
Views: 97
Reputation: 173
The default behavior of printing a pointer with operator<<
is to print the hex representation of the memory address being pointing at.
When the implementation of print()
is inside the class declaration, the compiler has not yet seen the operator<<
override for a Student*
pointer, so it doesn't know that it should behave any differently than the default.
When you define the print()
implementation after the operator<<
override, the compiler knows to use that override instead of the default.
Upvotes: 6