Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding function to string class

I understand that inheriting from std::string class is a poor idea, but was just trying to add a custom function to string class for a dummy assignment, using inheritance. I want to call my function as 'add' and when I do str.add(str1,str2); it should append str1 at the beginning of the string and str2 at the end of the string. This class(inherited string class) is a private member class of another class(say Parent). when I try to access my string class object with this, it points to the Parent class. How can I do this?

Thanks

like image 230
keeda Avatar asked Mar 29 '26 17:03

keeda


1 Answers

I'm not sure I understand all aspects of your question. When you say a private member class, do you mean private member variable? Or is it privately inheriting? I don't understand "when I try to access my string class object with this, it points to the Parent class".

You're right, inheriting from std::string is probably not a very good idea. First of all, making it a member of a derived string requires that you know quite a lot about the underlying implementation; this may change from distribution to distribution making the code non-portable. If you do write an implementation that is portable, using the already-defined interface provided by std::string, you won't be able to take advantage of any real optimization anyway. Unless you have a really good reason for this, you're better off not doing it at all.

Second, the name "add" is probably not the best, as it doesn't seem to describe what you're doing. "surround" may be a better name.

I think an external function like this might be better, avoiding the whole idea of inheriting from string:

void surround(std::string &orig, std::string const &pre, std::string const &post) {
    orig = pre + orig + post;
}

or, if you want higher performance, do something like this:

void surround(std::string &orig, std::string const &pre, std::string const &post) {
    std::string str;
    str.reserve(orig.size() + pre.size() + post.size());
    str.insert(str.end(), pre.begin(), pre.end());
    str.insert(str.end(), orig.begin(), orig.end());
    str.insert(str.end(), post.begin(), post.end());
    std::swap(str, orig);
}
like image 196
graphicsMan Avatar answered Apr 01 '26 07:04

graphicsMan



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!