Question

I'm working on a C++ project that deals with graphs. It has a lot of functionality related to a class "Node" and a class "Edge."

At first, an Edge stored copies of its starting node and its ending node; something like:

class Edge{
...
private:
  Node m_start, m_end;
...
}

To make certain graph modification functions more efficient, I decided to make the Edge class store pointers to the start and end nodes instead:

class Edge{
  ...
  private:
    Node* m_start, m_end;
  ...
}

I thus made adjustments in the cpp files/related functions to ensure proper access (e.g., changing .s to ->s). One example is in a printing function:

void
Edge::Print(ostream& _os){
  _os << "EdgeID = " << m_id << endl
  << "Connects nodes: " << m_start->GetIndex() << " and " << m_end->GetIndex() << endl;
}

But when I try to compile, I get this message (and similar ones for the same kinds of changes elsewhere):

Models/Edge.cpp: In member function ‘virtual void Edge::Print(std::ostream&) const’:
Models/Edge.cpp:32: error: base operand of ‘->’ has non-pointer type ‘const Node’

[where 32 is the line in the example above that starts with << "Connects nodes: "]

What is going on here? m_start IS a pointer, as far as I can tell! Might there be something wrong in assignment somewhere? The GetIndex() function being called in the example looks like this, and the same error occurs with or without the const:

int GetIndex() const { return m_index; }  //in Node.h
Was it helpful?

Solution

You've shot yourself in both feet. It should be:

Node* m_start, * m_end;

Next time, just pay the extra screen line and write:

Node * m_start;
Node * m_end;

You'll be doing everyone a favour.

OTHER TIPS

Node* m_start, m_end;

This declares m_start as a Node*, but it declares m_end as a Node. The code to make them both pointers would look like this:

Node* m_start, *m_end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top