I have only been using c++ for about a month now and I was wondering if it were possible to create your own custom functions for something like a string.
For example to find the size of a string you do stringname.size() But what if I wanted to make a function like stringname.customfunction() were I get to decide what customfunction() does. I want to do this so I can create a .toLower() function that converts a whole string to lower. I'm sorry if this is a wierd question but any help would be greatly appreciated.
4 Answers
Yes you can create custom functions, but not directly as member functions of an existing class.
The simplest and therefore best approach is to just create freestanding functions.
That means that you'll call it like customfunction( s ).
1 Comment
You can achieve this by creating you own string class, but as I've undertood you mean calling something like "THE String".toLower() as in python for example. This is actually imposible in c++ as far as I know.
Once again your best chance is do your own class so you can call someting like MyString("THE String").toLower(). Or just create a function toLower that takes an string and return an string toLower("THE String")
Comments
You can't directly but you should be able to emulate this by inheriting from std::string (or basic_string<char>):
class mystring : public std::string
{
public:
void customfunction() { /* ... */ }
};
Note: However doing so is a bad idea. In addition to the link that @Cheers and hth. - Alf mentions, Herb Sutter discusses the overly wide interface of std::string and widening it even further is a bad idea.