In Java every Object has a toString method and a hashcode method. Is there an equivalent hashcode and toString for each object in C++?
Asked
Active
Viewed 1,103 times
3
-
7Nope. If you want that you have to write it. – NathanOliver Apr 18 '18 at 15:18
-
2Possible 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
-
1There 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
-
1No 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 Answers
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
-
-
Darn. Well I guess I will just have to infiltrate apple headquarters and hit the CEO with a pipe until he agrees to give good java support :) – mackycheese21 Apr 20 '18 at 17:08
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