Overloading << operator

Mar 14, 2013 at 11:43pm
Having trouble overloading the << operator while working on a project. I made a pretty simple class to test it separately. It links fine however the program keeps crashing. On UNIX it defines it as a segmentation fault. I don't know what im doing wrong. Help would be much appreciated.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#ifndef DEMO_H
#define DEMO_H
#include<iostream>
using namespace std;

class Demo
{
	private:
		int count;
	
	public:
		Demo();
	friend ostream & operator << ( ostream &,const Demo &);	
		
};

Demo::Demo()
{
	count=5;
}

ostream & operator<<(ostream & leftOp, const Demo & rightOp)
{
	leftOp<<rightOp;
	return out;
	
}





1
2
3
4
5
6
7
8
9
#include "Demo.h"



int main()
{
	Demo show;
	cout<<show;
}
Mar 14, 2013 at 11:48pm
Where do you define operator << for Demo? (line 13 in Demo.h)
Mar 15, 2013 at 12:21am
I'm not sure what you mean, could provide an example?
Mar 15, 2013 at 12:43am
1
2
3
4
5
6
ostream & operator<<(ostream & leftOp, const Demo & rightOp)
{
	leftOp<<rightOp;  // <- this keeps calling itself
	return out;
	
}


your operator keeps calling itself infinitely. So this will just keep calling itself and calling itself until you run out of stack space and the program explodes.

In this << operator, you have to tell it what to print. You can't tell it to print the Demo object like you are, because you are defining how the Demo object is supposed to be printed.

Something like this would make more sense:

1
2
3
4
5
ostream & operator<<(ostream & leftOp, const Demo & rightOp)
{
	leftOp<<rightOp.count;  // <- print the count
	return out;
}
Mar 15, 2013 at 1:40am
@OP
It looked to me like you were using the overload on line 22 to call the overload on line 13, which is why I asked where/if you defined it. But you can ignore that now, Disch was spot on.
Topic archived. No new replies allowed.