Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toString override in C++ [duplicate]

Tags:

c++

tostring

In Java, when a class overrides .toString() and you do System.out.println() it will use that.

class MyObj {     public String toString() { return "Hi"; } } ... x = new MyObj(); System.out.println(x); // prints Hi 

How can I accomplish that in C++, so that:

Object x = new Object(); std::cout << *x << endl; 

Will output some meaningful string representation I chose for Object?

like image 472
Aillyn Avatar asked Mar 02 '11 18:03

Aillyn


People also ask

What happen if we override toString () method?

We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.

What is toString override?

Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.

Why do we override toString?

By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.


2 Answers

std::ostream & operator<<(std::ostream & Str, Object const & v) {    // print something from v to str, e.g: Str << v.getX();   return Str; } 

If you write this in a header file, remember to mark the function inline: inline std::ostream & operator<<(... (See the C++ Super-FAQ for why.)

like image 182
Erik Avatar answered Oct 02 '22 06:10

Erik


Alternative to Erik's solution you can override the string conversion operator.

class MyObj { public:     operator std::string() const { return "Hi"; } } 

With this approach, you can use your objects wherever a string output is needed. You are not restricted to streams.

However this type of conversion operators may lead to unintentional conversions and hard-to-trace bugs. I recommend using this with only classes that have text semantics, such as a Path, a UserName and a SerialCode.

like image 44
Tugrul Ates Avatar answered Oct 02 '22 06:10

Tugrul Ates