yairabr yairabr - 1 year ago 65
C++ Question

string overloading operator ">>"

hey i created an abstract class called "Node" and and class NodeBlock that implements the Node class. in my main class i need to print the values that inside the NodeBlock this is some of my code for the main class:

//receving the fasteset route using the BFS algorithm.
std::stack<Node *> fast = bfs.breadthFirstSearch(start, goal);

/*print the route*/
while (!fast.empty()) {
cout << fast.top() << endl;


#include <vector>
#include "Point.h"
#include <string>

using namespace std;

* An abstract class that represent Node/Vertex of a graph the node
* has functionality that let use him for calculating route print the
* value it holds. etc..
class Node {
vector<Node*> children;
bool visited;
Node* father;
int distance;

* prints the value that the node holds.
virtual string printValue() const = 0;

* overloading method.
virtual string operator<<(const Node *node) const {
return printValue();




#include "Node.h"
#include "Point.h"
#include <string>

class NodeBlock : public Node {
Point point;

* prints the vaule that the node holds.
ostream printValue() const override ;


#include "NodeBlock.h"
using namespace std;

NodeBlock::NodeBlock(Point point) : point(point) {}

string NodeBlock::printValue() const {
return "(" + to_string(point.getX()) + ", " + to_string(point.getY());

i deleted all the unnecessary method of those class. now i'm trying to overload the << operator so when i top.() from the stack it will and assign it to the "cout" it will print the string of the point.

but my current output is:

which as you know is the address. thanks for the help

qxz qxz
Answer Source

What you're looking for is a << operator that has an ostream on the left and a Node on the right, and evaluates to the same ostream. Thus, it should be defined like this (outside of the Node class):

std::ostream& operator<<(std::ostream& out, const Node& node) {
    out << node.printValue();
    return out;

Then you need to make sure that you're couting a Node, not a Node*:

cout << *fast.top() << endl; // dereference the pointer
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download