rahman
rahman

Reputation: 4948

Another "invalid initialization of reference of type" error

I have container in my class like this:

protected:
std::map<const AAA*, std::set<BBB*> > conn;

Both of the following getter functions works just fine:

std::map<const AAA*, std::set<BBB*> > & getConnectors()       {return connectors;}
std::map<const AAA*, std::set<BBB*> >   getConnectors() const {return connectors;}

but & and const together, Nope.Gives error:

std::map<const AAA*, std::set<BBB*> > & getConnectors() const {return connectors;} //error

Error is:

/home.../Multi.hpp:65:108: error: invalid initialization of reference of type ‘std::map<const AAA*, std::set<BBB*> >&’ from expression of type ‘const std::map<const AAA*, std::set<BBB*> >’
make[2]: *** [CMakeFiles/SimMobility.dir/main.cpp.o] Error 1

why I am getting this and How may I solve it please

thank you

Upvotes: 0

Views: 9515

Answers (2)

SJinxin
SJinxin

Reputation: 85

the last one should be written as

const std::map<const AAA*, std::set<BBB*> > & getConnectors() const {return connectors;}

Upvotes: 1

Kos
Kos

Reputation: 72271

This doesn't work because from a const method all members (besides mutable) should be treated as if they are const themselves.

This means that not only you can't modify them from that method, but also you can't point to them with a pointer to non-const or form a reference to non-const.

Hence, use:

      std::map<Foo, Bar> & GetConnectors();
const std::map<Foo, Bar> & GetConnectors() const;

Upvotes: 5

Related Questions