Start New Discussion within our Software Development Community

Hi All,

I am facing issue again and would be great if you help me to understand this code:

#include <iostream>
#include <ostream>
using namespace std;

class A{
	int a;
	A(int a):a(a){

	A operator+(A &other){
		A aaa(a+other.a);
		return aaa;

	friend ostream& operator<<(ostream &stream, A &aa){
		stream << aa.a;
		return stream;


int main() {
	A a1(2);
	A a2(4);

	A tmp = a1+a2;
	cout << tmp;  //this works fine. prints 6

	cout << (a1+a2) << endl; //Gives error, why its not able to use overloaded output operator
	return 0;

This is the error I am getting

error: no match for ‘operator<<’ in ‘std::cout << a1.A::operator+(a2)’
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc:67: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]

How do i overload << for such a scenario? or am I missing something?

Thanks guys.

This question has already been answered. Start a new discussion instead.