DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++ Overloading << operator of std::cout

To use std::cout for printing a custom object, we need to overload the << operator. In most cases, we require the friend keyword to access non-public members of the class.

#include <iostream>
using namespace std;
class A {
    int val;
public:
    A(int v) : val(v) {}
    friend ostream& operator<<(ostream& os, const A& obj) {
        os << obj.val;
        return os;
    }
};
int main() {
    A obj(42);
    cout <<"Value = "<< obj << endl; // Output: Value: 42
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas
  1. You don't have to use std::cout. You can use any ostream.
  2. You neglect to mention that the overload of << must be a non-member function — which is why you need friend.
Collapse
 
dinhluanbmt profile image
dinhluanbmt

you are right^^