Hello all, I'm a C++ rookie learning about operator overloading so bare with me here. I am trying to find some help on how to use the overload operator << in ways other then to stream something to cout. An example would be having 2 account balances and trying to transfer the balance of one to the other.
So in main you would see the line something like this:
account2 << account1;
I guess I have 2 questions on this. The first, is how would I go about declaring the << operator in a header file?
friend ostream& operator<<(ostream& , const Account&); would work if I was streaming something to cout. But, I'm confused as to how you go about this when cout isnt involved. And, I'm also looking for ways to write the member function to get something like account2 << account1 to work. Thanks.
I would make an account class and overload the operator in that class. Presumably, when you "transfer" a balance, you also want to add to the balance in the account transferring to and deplete the balance of the other account. This behavior should be represented in the overload.
[sarcasm]Wow, Vlad, what in informative and insightful piece of criticism.[/sarcasm]
To what are you referring? The fact that one account has the authority to wipe the balance of the other due to the lack of a const keyword? As mentioned in the original post, it was a quick example and any specifics really should be addressed by the OP when implementing it specifically.
But if you want to be specific, I could have quite have easily pointed out that you're code can also be considered 'very bad'. I say this because if you work in the bank of Vlad and want to transfer a balance, like the OP said, then you may be somewhat dismayed to find out that all of your account details, including account numbers and sort codes, have been overwritten by the bank's balance transfer algorithm.
But it would be pretty pedantic of me to point that out.
If you're going to criticise then please do, I encourage it. I genuinely think that learning from the advice and criticism of other is the best way to learn and this will be evident where other people have commented on my code in other posts. However, if you're going to leave snarky, one-liner comments than save a bit of time for both of us and don't bother.
iHutch105,
I am sorry that I did not pointed out why your code is bad.
Firstly it is a bad idea to assign names to variables that starts from underluing symbol as _balance, because such names are reserved for internal names of the compiler inplementation and system API.