Aparajithan Venkateswaran Aparajithan Venkateswaran - 1 year ago 39
C++ Question

How do I overload the << operator to print a class member?

Here is the class

class graph {
graph() {}; // constructor
graph(int size);
friend ostream& operator<< (ostream& out, graph g);
int size;
bool** grph;

This is how I generate the graph:

graph::graph(int size) {
grph = new bool*[size];
for (int i = 0; i < size; ++i)
grph[i] = new bool[size];
for (int i = 0; i < size; ++i)
for (int j = i; j < size; ++j) {
if (i == j)
grph[i][j] = false;
else {
cout << prob() << endl;//marker
grph[i][j] = grph[j][i] = (prob() < 0.19);
cout << grph[i][j] << endl;//marker
cout << "Graph created" << endl;//marker

The constructor and the prob() function work just fine. I have tested them using the markers.

This is where I believe the problem exists. This is the code for the overloaded operator <<

ostream& operator<< (ostream& out, graph g) {
for (int i = 0; i < g.size; ++i) {
for (int j = 0; j < g.size; ++j)
out << g.grph[i][j] << "\t";
out << endl;
return out;

Here is how this is called.

graph g(5);
cout << g << endl;

Now, the program compiles just fine. But, while execution, the graph is not being printed. I haven been able to print the graph the same way without overloading the operator, but by having the for loops run inside the main or by using a class member function.

Can anyone help me out? I am using Visual Studio 2015.

Answer Source

The loops are never entered, because

i < g.size

is always false, because g.size is 0! You are never actually setting the member variable size to the size entered by the user, so it defaults to 0.

You'll have to set it, i.e.

this->size = size; //Sets member variable 'size' to 'size' from the function arguments