4

I'm stuck on an error from so long now, the following, I'm learning and I think I don't understand the error.

 droid.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Droid&)’: 

droid.cpp:94:30: error: passing ‘const Droid’ as ‘this’ argument of ‘std::string 

Droid::getId()’ discards qualifiers
 [-fpermissive]

the line 94:

std::ostream&   operator<<(std::ostream &os, Droid const & a)
    os << "Droid '" << a.getId() << "', " << *a.getStatus() << ", " << a.getEnergy() << std::endl;

and hearders :

std::string   getId();

I have the same error for the 3 calls in "operator<<", a.getId, a.getStatus, a.getEnergy.

Can someone could explain to me what the compiler is saying?

Alistra
  • 5,177
  • 2
  • 30
  • 42
Gabson
  • 421
  • 1
  • 4
  • 20

2 Answers2

10

You need to make that method const so it can be called on a const instance or via a const reference:

std::string   getId() const;
                      ^^^^^

The same would apply to all Droid methods called in std::ostream& operator<<(std::ostream &os, Droid const & a).

You will also need to add the const in the method's definition.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • @juanchopanza Would you mind please to mention how is it called? I would like to understand why I need to declare `const` on reference explicitly. – Cron Merdek Apr 06 '16 at 13:17
3

You need std::string getId() const;. Otherwise, the compiler thinks getId() might change the instance, which you can't do on a const Droid&. Same thing for getStatus() and getEnergy().

Fred Larson
  • 60,987
  • 18
  • 112
  • 174