Somnium

C++: X to String

⇜ back to C++

In Python it's very easy to make an object printable using the __str__ method. Here's an example:

class Num:
    def __init__(self, n):
        self.n = n

    def __str__(self):
        return str(n)

if __name__ == '__main__':
    print(Num(55))

The C++ version is a bit different. You don't declare a method in a class, but overload the << operator with a function that accepts an instance of your class. Here's an example:

#include <iostream>
#include <string>

class Num {
public:
  const int n;
  Num(int n) : n(n) {}
};

std::ostream &operator<<(std::ostream &out, const Num &b) {
  return out << std::to_string(b.n);
}

int main() {
  auto a = Num(55);
  std::cout << a << "\n";
  return 0;
}

In case you need to access private and protected class member you can add a friend declaration to the class. Something like the following:

friend std::ostream &operator<<(
  std::ostream &out,
  const Num &b);

References