code_junkie

In c++, why does the compiler choose the non-const function when the const would work also?

Nov 11th, 2011
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.44 KB | None | 0 0
  1. class Foo
  2. {
  3. public:
  4. std::string& Name()
  5. {
  6. m_maybe_modified = true;
  7. return m_name;
  8. }
  9.  
  10. const std::string& Name() const
  11. {
  12. return m_name;
  13. }
  14. protected:
  15. std::string m_name;
  16. bool m_maybe_modified;
  17. };
  18.  
  19. Foo *a;
  20. // Do stuff...
  21. std::string name = a->Name(); // <-- chooses the non-const version
  22.  
  23. const Foo* b = a;
  24. std::string name = b->Name();
  25.  
  26. std::string name = b->Name();
  27.  
  28. b->Name() = "me";
Add Comment
Please, Sign In to add comment