Search code examples
javascriptc++square-bracket

How to dynamically call property names in C++ like square bracket notation in JS?


My first language is Javascript, but I'm starting to learn C++. One of my favorite things to do is access properties with clever variable property names using square bracket notation in Javascript like so:

var a = "prop";
var obj = {
  this.prop : "before"
};
function alterObj(a){
  obj[a] = "after";
}

It doesn't seem to be coming up in my C++ books, and I'm having trouble Googling it. So how does one dynamically select property names in C++?


Solution

  • The short answer is one cannot do this in c++. A major difference between c++ and javascript are that c++ is a compiled language whereas javascript is not. Javascript has a lot of neat runtime features that you can use, i.e. you can use bracket notation to access properties

    obj["property"]
    

    This allows any sort of string to be placed in the brackets and then evaluated at runtime. C++, however does not have as large of a runtime (there is a very powerful runtime, but powerful in a different way).

    Now with all this said if you wanted to implement a function like your alterObj above you could use the map class. Also you can overload the [] operator. The following snippet gives an example:

    #include <iostream>
    #include <map>
    
    class SpecialObject {
      public:
      std::string operator[](std::string key);
    };
    
    std::string SpecialObject::operator[](std::string key) {
      std::string retVal = key + " whoa!";
      return retVal;
    }
    
    void modify(std::map<std::string, std::string> &obj) {
      obj["something"] = "someone else";
    }
    
    int main(int argc, const char *argv[]) {
      std::map<std::string, std::string> obj;
      obj["something"] = "someone";
      modify(obj);
      std::cout << "obj[\"something\"] = " << obj["something"] << std::endl;
    
      SpecialObject obj2;
      std::cout << "obj2[\"The clowns say\"] = " << obj2["The clowns say"] << std::endl;
      return 0;
    }
    

    The map object allows you to create a simple container for other objects (in some sense exactly like what javascript objects are) and the SpecialObject class shows how you can implement the [] operator yourself.