I come from the python world where __str__
and __repr__
have been very useful to my development and execution workflow output.
I would like to implement such things in C++.
This post has been useful, however I would like that the string output includes the class name and that it be easily overloadable by subclasses.
Here is a code example:
#include<iostream>
#include<string>
class Parent
{
static constexpr const char* clsName = "Parent";
std::string _label;
public:
Parent(std::string& label) : _label(label) {}
friend std::ostream &operator<<(std::ostream &os,
Parent const &ref)
{
os << clsName << "(";
ref.print(os);
os << ")";
return os;
}
void print(std::ostream &os) const
{ os << _label; }
};
class Child : public Parent
{
static constexpr const char* clsName = "Child";
public:
Child(std::string& label) : Parent(label) {}
};
My intent here is that the Child::operator<<
use it own clsName
static private data, without having to overload the whole operator for each subclass.
Unfortunately this strategy does not work:
int main()
{
std::string l("some label");
Child x(l);
std::cout << x << std::endl;
}
Will output
Parent(some label)
(I would like to see Child(some label)
).