Help understand overloading operators

I'm going through an ebook ( http://www.e-booksdirectory.com/details.php?ebook=5576) "Beginning C++ Through Game Programming." I'm at the point of overloading operators and this code gets a little cryptic to me. In the program, the << operator is overloaded. The overload function is made a friend function and is defined outside the class.

For clarity's sake, what would the same operator overload function look like if declared as a public class function?

And, how else could it be call with out using the << operator? e.g., from the C++ tutorial here:

"The function operator+ of class CVector overloads the addition operator (+) for that type. Once declared, this function can be called either implicitly using the operator, or explicitly using its functional name:



c = a + b;
c = a.operator+ (b); "

How would you call the << operator function explicitly?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  //Friend Critter
//Demonstrates friend functions and operator overloading
#include <iostream>
#include <string>
using namespace std;
class Critter
{
	//make following global functions friends of the Critter class
	friend void Peek(const Critter& aCritter);
	friend ostream& operator<<(ostream& os, const Critter& aCritter);
public:
	Critter(const string& name = "");
private:
	string m_Name;
};
Critter::Critter(const string& name) :
m_Name(name)
{}
void Peek(const Critter& aCritter);
ostream& operator<<(ostream& os, const Critter& aCritter);
int main()
{
	Critter crit("Poochie");
	cout << "Calling Peek() to access crit’s private data member, m_Name: \n";
	Peek(crit);
	cout << "\nSending crit object to cout with the << operator:\n";
	cout << crit;
	return 0;
}
//global friend function which can access all of a Critter object’s members
void Peek(const Critter& aCritter)
{
	cout << aCritter.m_Name << endl;
}
//global friend function which can access all of Critter object’s members
//overloads the << operator so you can send a Critter object to cout
ostream& operator<<(ostream& os, const Critter& aCritter)
{
	os << "Critter Object - ";
	os << "m_Name: " << aCritter.m_Name;
	return os;
}
Last edited on
For clarity's sake, what would the same operator overload function look like if declared as a public class function?
You cannot do that.
Operator defined inside class will have a reference to that class as left hand argument. However for IO operators left hand operand should be stream.

This is the reason why we have to define it outside class.
I'm getting a better understanding, thanks.
Topic archived. No new replies allowed.