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
  • 884
  • 1
  • 9
  • 24
  • 7
    Nope. If you want that you have to write it. – NathanOliver Apr 18 '18 at 15:18
  • 2
    Possible duplicate of [Can I implement .ToString() on C++ structs for debugging purposes?](https://stackoverflow.com/questions/26597189/can-i-implement-tostring-on-c-structs-for-debugging-purposes) – Nikolai Shevchenko Apr 18 '18 at 15:18
  • 1
    There is [std::to_string](http://en.cppreference.com/w/cpp/string/basic_string/to_string) for built-in types, but that's it. – Jesper Juhl Apr 18 '18 at 15:23
  • @JesperJuhl one can specialise it for custom types too – UKMonkey Apr 18 '18 at 15:25
  • @UKMonkey Sure, but I got the impression that OP was asking about what was available off the bat. – Jesper Juhl Apr 18 '18 at 15:27
  • 1
    No everithing has sense. Most similar techniques in Java/C# have sense only with reflection – Jacek Cz Apr 18 '18 at 15:29
  • The most universal way to stringize objects in C++ is to [provide an overload of `operator <<` for `std::ostream`](https://stackoverflow.com/q/476272/7571258) and on some platforms like Windows also `std::wostream`. Doesn't work automatically for all types, but the nice thing about this mechanism is that you can write your own overload if the original author of the type doesn't provide one. – zett42 Apr 18 '18 at 15:49

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
  • 14,674
  • 4
  • 34
  • 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
  • 381
  • 3
  • 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