7

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 4

4

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
  • so instead of stringname.customfunction() the preferred way is customfunction(string a). Alright I think I understand now. Nov 13, 2015 at 8:32
4

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")

3

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.

2
  • SO was very slooooow here for a while, but here's a link to more info: (stackoverflow.com/questions/6006860/…). The accepted and heavily upvoted answer is ungood – not uncommon on SO – but there are good points made. Nov 13, 2015 at 10:44
  • I didn't say it was best practice - I merely presented it as a way of doing it. Where I work we have 6 different string classes, two of which are home grown. I will update the answer to note that it is a bad idea. Nov 13, 2015 at 12:14
1

This may be a bit advanced and highly despised, but you could change the actual source files. I highly suggest YOU DO NOT do this.

You should just make a simple function void toLower(std::string str); that would convert it for you. (You would call this function with toLower(str);.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.