2

I have a header file that contains a class. Within that class, I have a function like so:

class Definition { public: int GetID() { return Id; } //Other methods/variables private: int Id; } 

When I attemped to get that ID as so:

for (std::map<Definition, std::vector<bool> >::iterator mapit = DefUseMap.begin(); mapit != DefUseMap.end(); ++mapit, defIndex++) { stream << "Definition " << (*mapit).first.GetID() << " Def Use" << endl << "\t"; } 

I get the following error

CFG.cc:1145: error: passing 'const Definition' as 'this' argument of 'int Definition::GetID()' discards qualifiers

is it because I'm using definition inside a map, and I'm not allowed to call methods on that mapped definition? Is there a way to get that ID variable out?

Thanks in advance

2 Answers 2

9

Declare the getID() method const:

int getId() const { return Id; } 

Then the method can be called by a const reference, which is what operator<<() is being passed.

Sign up to request clarification or add additional context in comments.

2 Comments

The general rule is to declare a method const if it only needs const access to the object, i.e. this could be a const pointer and things will work just fine. Also note the mutable keyword, which says that a class member can be changed even in a const method. One example of a mutable member is if you wanted to record the last access time for an object. In this case, the access timestamp would be a mutable member so it could be updated from a const getter method.
user127817 -- if you find my answer satisfactory, please consider accepting it. Thanks!
1

The map<Key, Value> stores your data internally in a std::pair<const Key, Value>. This so that it will be hard to accidentally change the Key and destroy the ordering of the elements.

To be able to call GetID() for the const Key, the function will have to be declared const as well:

int GetID() const; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.