Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange const correctness error

Tags:

c++

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

like image 953
Megatron Avatar asked Mar 25 '26 01:03

Megatron


2 Answers

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.

like image 83
QuantumMechanic Avatar answered Mar 26 '26 14:03

QuantumMechanic


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;
like image 33
Bo Persson Avatar answered Mar 26 '26 15:03

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!