Overriding<< operator

Hi i am new to C++ and i am working on a project where i override the output operater << using a friend method i know how to do this for a regular output where cout << is used however my teacher has provided a main method for me to test my results on and he does not use cout he uses output from ofstream which i dont quite understand a more abstract simpler example of what i am dealing with is posted below:

This works
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
#include <iostream>
using namespace std;

class Date
{
    int mo, da, yr;
public:
    Date(int m, int d, int y)
    {
        mo = m; da = d; yr = y;
    }
    friend ostream& operator<<(ostream& out, Date& dt); 
// friend method to ovveride output
};

// implementation of friend method
ostream& operator<<(ostream& out, Date& dt)
{
    out << dt.mo << '/' << dt.da << '/' << dt.yr;
    return out;
}

int main()
{
    Date dt(5, 6, 92);
    cout << dt; // cout is overiden and this works
}

OutPuts the date like 5/6/92

Now using my teachers main method provided
This Doesnt Work:

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
#include <iostream>
#include <fstream> // fstream is included 
using namespace std;

class Date
{
    int mo, da, yr;
public:
    Date(int m, int d, int y)
    {
        mo = m; da = d; yr = y;
    }
    friend ostream& operator<<(ostream& out, Date& dt); // same friend method
};

// same implementation
ostream& operator<<(ostream& out, Date& dt)
{
    out << dt.mo << '/' << dt.da << '/' << dt.yr;
    return out;
}

// my teachers main
int main()
{
	ofstream output("output",ios::out); // this used instead of cout?
	if (output == NULL)
	{
		cerr << "File cannot be opened" << endl;
		exit(0);
	}
    Date dt(5, 6, 92);
    output << dt; // absolutly nothing is output "press any key to continue"
}


Please could someone explain why this isnt working for my teachers main method but it does for mine? and how can i fix this so i get the same output for both.
Thank You i hope i have explained everything well enough please just ask if you need clarification
Solved Looked in the project directory and it created a file called output and my output was sent here :)
Even better than making that a friend would be to have getter methods to return copies of the month, day, and year so you can use them in your overload.

Friend functions work but they can compromise you class's integrity because now the client has full access to your private data that function.

Just something to consider.
Topic archived. No new replies allowed.