devxlogo

Use the Generic Accessors Class

Use the Generic Accessors Class

Generally, from an OOP perspective, the direct access to data members should be prevented. This is why we use accessors:

  Class UserDetails{public:    string getUserName() const;    void setUserName(const string& name);     string getUserLastName() const;     void setUserLastName(const string& name);      private:    string userName;    string userLastName;};

Using this technique gets tricky in the case of a changeable class. For every member you we add, you have to implement its accessors. This can get tedious if you’ve got a lot of members.

In this case, you can use the ‘generic accessors class’. This class allows you to change the class structure without any modification:

  Class GenericDataHolder : public map{public:    string get(const string& paramName)     {            string ret("");        iterator iter = find(paramName);         if (iter!=end())            ret = (*iter).second;        return ret;    }     void set(const string& paramName,const string& value)     {            insert(value_type(paramName,value));    }};  Class UserDetails : public GenericDataHolder {};  void main(){    UserDetails details;        details.set("Name","abc");    details.set("LastName","abc");    details.set("Age","10" );};
See also  Redefining Energy Management: Advanced Solutions for Modern Buildings
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist