chevron_left
226 points
13 6 3

In C++, when you use arithmetic operations, you use some symbols like “+”, “-”, “*”, “/”, …. Apart from that, there are also others symbol that are used for special purposes like “=” for assignment, “.” for object’s member accessment and so on. However, not all C++ learners know that we can change operations which are bound to these operators and this is called operator overloading. In this article, I will show you how to overload ”<<” operator in C++. So let’s begin !

In most cases, you can use the “<<” operator for printing data to the standard stream:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World !" << endl;
}

or to carry out left-byte shifting operations:

Example: For example, 1 in binary is 001, and if we shift 1 bit of 1 to the left, we will get 010, which is 2.

#include <iostream>

using namespace std;

int main()
{
    int val = 1;
    int newVal = (val << 1);    // shift 1 bit to the left
    cout << newVal << endl;
}

Result:

2

Generally, in C++ we use the following syntax to overload a operator:

<DataType> operator<operator> (DataType var)

Example: Class Point has 2 attributes: x and y. Now we will overload the << operator to print out the coordinate of a Point object:

#include <iostream>

using namespace std;

class Point
{
private:
    int x;
    int y;

public:
    friend ostream & operator << (ostream &out, const Point & point);   // to access attributes of the class object

    Point(int _x, int _y)
    {
        this->x = _x;
        this->y = _y;
    }
};

ostream & operator << (ostream &out, const Point & point)
{
    cout << "(" << point.x << ", " << point.y << ")";
    return out;
}

int main()
{
    Point p1(1, 3), p2(5, 7), p3(2, 4);
    
    cout << p1 << endl;
    cout << p2 << endl;
    cout << p3 << endl;
}

Result:

(1, 3)
(5, 7)
(2, 4)

I have explained to you why we need operator overloading and shown an example that involves overloading << to print data of a C++ class.
If you like this article, please give a yes or heart.

Happy coding !

1 Comment

If you want to know more about the operator, you can. I have tried my best. Thank u so much. Continue to post:)

More Posts

-> operator in C++ hhh98hd - Aug 7
.* operator in C++ sakshi - Aug 5
What does ~ mean in c++. Tania - Sep 16
How to compare strings in C++? Lalit Kumar - Jun 14, 2020
C++ operators that cannot be overloaded sakshi - Jun 24
Unary operator in C++ Yogesh Sharma - Aug 1
operator overloading in c++ using friend function Lalit Kumar - Oct 14, 2020
No match for "operator <<" c++ Naymul01 - 5 days
No operator << matches these operands C++ Lalit Kumar - Sep 15, 2020
No operator matches these operands C++ Lalit Kumar - Apr 22, 2020