I had a midterm in c++ and one of our assignments was to write a class, that overloads the <<
operator so that we could print private fields of that class to std::ostream
, like so:
Crate c1(2600, 9500);
Crate c2;
cout << c1 << ", " << c2 << endl;
had to print Crate weight: 2600 Crate value: 9500, Crate weight: 0 Crate value: 0
My implementation of this was
class Crate {
int weight;
int value;
public:
Crate ():weight(0), value(0) {}
Crate (int w, int v);
Crate& operator+= (Crate& c);
int operator+= (int& w);
friend ostream& operator<< (ostream& out, Crate c) {
out << "Crate weight: " << c.weight;
out << " Crate value: " << c.value;
return out;
}
};
However, I got 0/3 points for the overloaded <<
operator, and the only difference between my solution and the evaluation template was that I pass Crate c
by value and they passed it by reference.
Of course, if the class would have dynamically allocated member variables, I would have to pass instances of it by reference, but this is not the case here.
I know that the example provided at cppreference.com uses a const reference, but is there any strict rule that one MUST use a const reference when doing this?
I understand that my solution copies both weight
and value
to the stack instead of only copying a pointer to the object, but is +4 bytes (in case of a 32 bit system) on the stack really that much of a problem, or am I missing something much more serious (like a memory leak of some sort)?
I also checked the disassembly of both solutions, but I couldn't find anything that would make my solution worth zero points.
I have also asked my professors but they started to talk about passing it as const
but I don't see how that would make this solution any better in terms of works / doesn't work. An other professor told me that "this is syntactically completely incorrect." however it compiled with Visual Studio and MinGW, so I can't make any sense of that either.
Please also note that this is a course for electrical engineers.