Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error passing 'const' as 'this' argument

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?

like image 289
Gabson Avatar asked Dec 11 '22 08:12

Gabson


1 Answers

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.

like image 100
juanchopanza Avatar answered Dec 26 '22 02:12

juanchopanza