This post will discuss how to print string representation of an object in C++.

In contrast to Java, C++ does not offer any implicit way to print an object. With C++11, std::to_string is added to the standard, which allows you to convert an integer to a std::string. However, C++ does not permit overloading of std::to_string for objects.

1. Overload operator<<

The standard solution to print an object implicitly in the output stream is to overload the operator<< for ostream. Now, whenever the string representation of an object is required, you can directly send the object contents to the output stream.

Download  Run Code

Output:

(1, 2)

 
In case you need to include the private and protected members of the class in its string representation, declare the operator<< as a friend function of the class.

Download  Run Code

Output:

(1, 2)

2. Using std::stringstream

Alternatively, you can use a string stream to get the string representation of the object and store it for later use.

Download  Run Code

Output:

(1, 2)

3. Creating toString() function

Finally, you can create a Java-style toString() function inside your class.

Download  Run Code

Output:

(1, 2)

That’s all about printing string representation of an object in C++.