DEV Community

dinhluanbmt
dinhluanbmt

Posted on

12

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^^

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay