Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Oct 26, 2001

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<string,string>
{
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" );
};
Mordehai Guri
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date