Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inherit from std::string or operator overloading

I want to have a class like below:

Class Test {
  Test();
  ~Test();
  ...
}

I want to be able to use following statement:

std::string str;
Test t;
str = t;

what should I do? should I override to_string? If yes it seems that it is not possible to inherit from std::string class. Or I have to override special operator? What about Pointer assignment? like below:

std::string str;
Test* t = new Test();
str = t;
like image 534
JGC Avatar asked Jun 24 '26 16:06

JGC


2 Answers

You can provide a user-defined conversion operator to std::string:

class Test {
  //...
public:
  operator std::string () const {
    return /*something*/;
  }
};

This will allow a Test object to be implicitly-converted to a std::string.

like image 125
TartanLlama Avatar answered Jun 26 '26 06:06

TartanLlama


Although in C++ it is possible, it is generally not advised to inherit from standard classes, see Why should one not derive from c++ std string class? for more info.

I am wondering, what is the function of the assignment of

str = t;

str is a std::string type, t is Test type. So what is the expected value of the assigment? No one can guess. I suggest to explicitly call a conversion method or an operator for code clarity.

This would make your example look like:

str = t.convertToString();

or the more standard way is to implement the stream operator, which makes

str << t;

(Note this example works if str is a stream type, if it is a string, you need further code, see C++ equivalent of java.toString?.)

But, if you really want it to work without a conversion method, you can override the string assignment operator of Test:

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

See also toString override in C++

Although this is a perfect solution to your question, it may come with unforeseen problems on the long run, as detailed in the linked article.

like image 21
Gee Bee Avatar answered Jun 26 '26 07:06

Gee Bee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!