Hani Gotc
Hani Gotc

Reputation: 890

Why did I have to change the type of a the value of a map from & to (int*)&

I have the function getElement that returns a pointer to a value of a map.

 int * getElement(const int &key) const {
        return (int*)&m.find(key)->second;
    }

If I use for instance return &m.find(key)->second it creates a compilation error:

In member function 'int* A::getElement(const int&) const': 12:30: error: invalid conversion from 'const int*' to 'int*' [-fpermissive]


#include <iostream>
#include <string>
#include <map>

class A {
    public:
    void addElement(const int &key, const int &value) {
         m.emplace(key,value);
    }
    int * getElement(const int &key) const {
        return (int*)&m.find(key)->second;
    }
    private:
    std::map<int,int> m;

};


int main()
{
  A a;
  int value = 1;
  int key = 1;
  a.addElement(key,value);
  int * x = a.getElement(1);
  std::cout << *x << std::endl;
  return 0;
}

Upvotes: 0

Views: 240

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Why do I have to change &m.find(key)->second to (int*)&m.find(key)->second

You don’t. In fact, doing so potentially creates an error. Instead, remove the const qualifier on your member function if you really want to modify the map values. Or return a const int* instead of an int* from the function.

To clarify, when you specify a member function as being const, then the this pointer inside that function becomes a pointer to a const instance of your class. This, in turn, makes its data members const, transitively.

As a consequence, your std::map<int, int> becomes a std::map<int, int> const inside your getElement function. Furthermore, std::map::find has an overload for const maps that returns a const_iterator — hence the const int*.

In fact, be careful: std::map::iterator isn’t necessarily T*. So you shouldn’t return int* or const int* — you should return std::map<int, int>::iterator (or …::const_iterator).

Upvotes: 5

Tyker
Tyker

Reputation: 3047

this membre fonction

int * getElement(const int &key) const

is constant so you can access all data membre as constant

and int* is different from const int*

Upvotes: 1

Related Questions