3

In Java every Object has a toString method and a hashcode method. Is there an equivalent hashcode and toString for each object in C++?

mackycheese21
  • 864
  • 1
  • 8
  • 22

2 Answers2

6

There is no equivalent. Unlike JAVA, not everything in C++ is derived from some (Object) superclass. There is no ::toString() member function as there is no superclass in C++ to begin with. C++ does not support reflection either.

That being said, there is a std::to_string function having 9 different overloads for the built-in types. To achieve the functionality you want, you can overload the output stream operator<< for each of your classes.

Ron
  • 13,936
  • 3
  • 30
  • 47
1

There's nothing like this built-in the language. Not everything in C++ is an object(there's no common class from which everything derives).

tomdol
  • 326
  • 4
  • 14
  • Besides functions, and maybe templates everything in C++ is an object. – NathanOliver Apr 18 '18 at 15:22
  • Comparing to Java, where everything(?) is a subclass of Object - there's no such thing in cpp. Of course ints, chars and everything else are PODs but there's no common interface for all of them. This is what I meant. – tomdol Apr 18 '18 at 15:23
  • There is a distinction between a class type and an object. There are many non-class type objects. It would be more accurate to say "Not everything in c++ is a class type." – François Andrieux Apr 18 '18 at 15:23
  • 2
    @tomdol Maybe rephrase it then that in C++, not everything is derived from a `Object` class? – NathanOliver Apr 18 '18 at 15:24