1

I want to create a function to data types like in javascript with "String.prototype". Is it possible in C++ too?

For example:

int functionName()
{
    if(this.string == "something") {
        return 1;
    }

    return 0;
}

std::string mystring = "text";

int result = mystring.functionName();

  • 1
    Not possible in C++. Not like that anyway. – Hatted Rooster Jul 17 '19 at 16:29
  • there are proposals for future c++ versions called _unified function calls_, they come very close to what you want to do. but unfortunately the future is not now. – local-ninja Jul 17 '19 at 16:52
  • Yeah, that's a big 'ol "nope!" Unfortunately for you, not a thing in C++. Maybe this is an [X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? Perhaps you can explain what you're trying to accomplish with this? –  Jul 17 '19 at 17:12
  • C++ is not scripting language, many things are done in a different way. Trying to use one language with habits from another usually lead to a disaster. – Slava Jul 17 '19 at 17:15

2 Answers2

3

No, it is not.

You can inherit from a class and add new members to the new derived class, but also consider composition because inheritance isn't always appropriate. Consult the chapter in your book about object oriented programming for more information on that.

Also consider free (non-member) functions if you don't need any access to private data. Similarly, be careful of overdoing it with the getters/setters!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

You can mimic extension functions in C++, by abusing free-standing operator overloading. Here I've leveraged operator->*.

#include <functional>
#include <iostream>
#include <string>

// Extension function.
static int functionName(std::string const& self) {
    if (self == "something") {
        return 1;
    }

    return 0;
}

// Thunk glue.
static int operator->*(std::string const& s, int(*fn)(std::string const&)) {
    return fn(s);
}

int main() {
    std::string s = "something";
    int i = s->*functionName;
    std::cout << i << "\n";
}

But I strongly urge you to wait until some future C++ standard formally adopts unified function calls.

Editorial note: not recommended, as it is not idiomatic C++ and abusing operator overloading is a good way to make you unpopular. And C++ is already a difficult enough language as is.

Eljay
  • 4,648
  • 3
  • 16
  • 27