A
A
Andrew_Rocket2020-02-19 23:40:36
C++ / C#
Andrew_Rocket, 2020-02-19 23:40:36

Is there a toString method for classes in C++?

In Java and C#, each class has a toString method that is called automatically when text is displayed and which can be overridden in each class in its own way.
Is there something similar in C++, or do I need to implement a separate method?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly, 2020-02-20
@Andrew_Rocket

No. Because C++ has a "don't pay for what you don't use" rule and there is no reflection at the language level.
If you want to stream a class, then implement: where Foo is your class. Well, if you need to cast a class to a string representation, then yes, you will have to implement the method by hand, or, which is more architecturally correct, make a separate class and / or function for conversion. ostream& operator<< (ostream& os, const Foo &o)

T
TriKrista, 2020-02-20
@TriKrista

No, do it yourself.

V
Vasily Melnikov, 2020-02-20
@BacCM

There are crafts with handwritten reflection. Anton Polukhin has a report, if I am not mistaken, on this topic.
But is it really necessary?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question