Search code examples
c++arraysmethodscharextend

C++ - extending a data type


Is there a way to extend a data type in C++, like you can in JavaScript?

I would imagine this is kind of like this:

char data[]="hello there";
char& capitalize(char&)
{
    //Capitalize the first letter. I know that there
    //is another way such as a for loop and subtract
    //whatever to change the keycode but I specifically 
    //don't want to do it that way. I want there
    //to be a method like appearance.
}

printf("%s", data.capitalize());

This should somehow print.


Solution

  • The closest you can get is using operator overloading, e.g.

    #include <iostream>
    #include <string>
    #include <cctype>
    #include <algorithm>
    
    std::string operator!(const std::string& in) {
      std::string out = in;
      std::transform(out.begin(), out.end(), out.begin(), (int (*)(int)) std::toupper);
      return out;
    }
    
    int main() {
      std::string str = "hello";
      std::cout << !str << std::endl;
      return 0;
    }
    

    Alternative approaches include creating a class with operator std::string overloaded and a constructor to initialize it using an std::string.