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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++ » Coding
Language: C
Expertise: Intermediate
Dec 29, 2003

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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('\0'), 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, double
const& 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 <iostream>

using namespace std;

class CUI
{
public:
  struct SOptions
  {
    SOptions() : m_bOption(false), m_cOption('\0'), 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;
};
George Anescu
 
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