Which method is better for implementing get/set?

Viewed 23066

There are two methos for implementing get/set.

Method 1:

Define get and set separately.

class my_class
{
  // ...
};

class main_class
{
public:

  my_class get_data() const
  {
    return m_data;
  }

  void set_data(my_class value)
  {
    m_data = value;
  }

private:

  my_class m_data;
};

Note: In this method get is fast enough: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value

And another method is (Method 2):

Define two get bodies, First const and another non const.

class my_class
{
  // ...
};

class main_class
{
public:

  const my_class& get_data() const
  {
    return m_data;
  }

  my_class& get_data() // Works like set.
  {
    return m_data;
  }

private:

  my_class m_data;
};

Using these methods:

void main()
{
  main_class cls;

  // For method 1.
  my_class data;
  data = cls.get_data();
  cls.set_data(data);

  // For method 2.
  const my_class data1;
  my_class data2;
  data1 = cls.get_data();  // const get invoked.
  cls.get_data() = data2; // Like set beacuase non const get invoked.

}

My question which of these methods for implementing get/set is better?

Do you know a better method?


Edit: For answers that believe Method 1 is better, what do you say in below situation:

void main()
{
  main_class cls;

  // For method 1.
  cls.get_data().do_something_else(); // Not effictive for cls, because data losts.

  // For method 2.
  cls.get_data().do_something_else(); // Effictive for cls.    
}
8 Answers
Related