Hi everyone,

I am quite new to C++ (coming from perl). As an exercise, I am currently trying to create a class to play with graphs.

I have a class Node in which I overload the == operator (to test the equality between two nodes). At the moment, I consider two nodes being similar if they have the same name.

When compiling I get the following error message.


Node.cpp: In member function ‘bool Node::operator==(const Node&)’:
Node.cpp:51: error: passing ‘const Node’ as ‘this’ argument of ‘std::string Node::getName()’ discards qualifiers


I would be very happy if somebody had an idea of the problem.

(Node.hpp)

class Node {
  
  public:
    Node(string);			
    Node(string, string);

    // blabla
    
    string getName();
    bool operator==(const Node &) ;

    // blabla


  private:
     string name;			// node name
};

(functions '==' and getName() in Node.cpp)

bool Node::operator==(const Node &node) {
  return node.getName() == getName();
}

string Node::getName() {
  return this->name;
}

Make your getName function a const corrected function like so :

string getName()const; //the const says that it will not change any member variable, presumably

//.cpp
string getName()const{
 return name;
}

And you should probably also make the operator == constant as well:

bool operator==(const Node &) const;

//.cpp
bool Node::operator ==(const Node& node) const {
  return node.getName() == getName();
};

The solution of firstPerson was the best one. It compiles without any problem now.

I also tried to make operator == constant as weel like Mike suggested but it does not change anything.

I thank you both for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.