0

For example, if you have an object of the std::string class, you can call the compare(string str) function as follows:

myString.compare(myOtherString);

How can I make my own function that I can call on a string in the same way? Example:

myString.contains(char[] chars);
3
  • @PiotrS.: I get the sense that that's the question OP is trying to ask. Commented Sep 9, 2014 at 12:26
  • 1
    You can switch to C# :D Commented Sep 9, 2014 at 12:26
  • If you're asking if you can add to an existing, closed, class definition, no, you can't. Commented Sep 9, 2014 at 12:27

2 Answers 2

1

You can't add member functions to existing classes in C++. Instead, write a non-member function

bool contains(std::string const & s1, std::string const & s2);

and call it as

contains(myString, myOtherString);
Sign up to request clarification or add additional context in comments.

Comments

0

You can't really do this in C++, and you shouldn't try. Sure, you could inherit from std::string and implement your methods, but then your methods will be unusable from regular strings. In C++ we do not try too hard to make everything a class method--free functions are functions too!

1 Comment

You could try, and end up with something like slideshare.net/phil_nash/c-extension-methods-18678294. But don't do this at home.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.