I am trying to overload << operator, so that when I use my class object in std::cout, it prints out the data members which is supposed to get printed.
I know I have to define a friend functions signature inside of a class, and then outside of the class I define two friend functions doing the job, but I want to hand over the class, and don’t want the user to do literally anything and I want the class take care of everything.
How can I achieve such a thing in C++?
C++ is designed to allow non-member functions to do things that would require a member function in other languages. A
friendfunction is very similar to a member function, in that it can be defined within a class scope. Also (and this can be confusing) if you declare afriendfunction only within a class scope, it can only be accessed by passing an object of that class to it.Although this subtle rule is odd at first, it reflects the idea that nonmember functions can also be encapsulated by the class.
For more info, read up on argument-dependent lookup (ADL).