devxlogo

A Multiple Getter/Setter Implementation

A Multiple Getter/Setter Implementation

Suppose you’ve got a user interface class with many user options that you need to set/get at the same time. Here’s one way to implement this:

class CUI{public:  CUI() : m_bOption(false), m_cOption(''), m_iOption(0), m_dOption(0.0){}  //...  void GetOptions(bool bOption, char cOption, int& riOption, double&rdOption)  {    bOption = m_bOption;    cOption = m_cOption;    riOption = m_iOption;    rdOption = m_dOption;  }  void SetOptions(bool bOption, char cOption, int const& riOption, doubleconst& rdOption)  {    m_bOption = bOption;    m_cOption = cOption;    m_iOption = riOption;    m_dOption = rdOption;  }private:  //...  bool m_bOption;  char m_cOption;  int m_iOption;  double m_dOption;};

The problem with this implementation is that when the number of options increases, you need to transfer a larger amount of data as arguments to the getter/setter functions. This is not an efficient way to make use of the program’s stack. The solution is to create an inner structure containing all the options:

#include using namespace std;class CUI{public:  struct SOptions  {    SOptions() : m_bOption(false), m_cOption(''), m_iOption(0),m_dOption(0.0) {}    bool m_bOption;    char m_cOption;    int m_iOption;    double m_dOption;  };  CUI() {}  //...  void GetOptions(SOptions& roOptions)  {    roOptions.m_bOption = m_oOptions.m_bOption;    roOptions.m_cOption = m_oOptions.m_cOption;    roOptions.m_iOption = m_oOptions.m_iOption;    roOptions.m_dOption = m_oOptions.m_dOption;  }  void SetOptions(SOptions const& roOptions)  {    m_oOptions.m_bOption = roOptions.m_bOption;    m_oOptions.m_cOption = roOptions.m_cOption;    m_oOptions.m_iOption = roOptions.m_iOption;    m_oOptions.m_dOption = roOptions.m_dOption;  }private:  //...  SOptions m_oOptions;};
See also  Why ChatGPT Is So Important Today
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