Search code examples
c++classobjectc++11data-members

When manipulating data members: which of the following is considered best practice


I want to start adopting best practice and have seen class members being manipulated in different ways. I am not aware of any subtle nor significant differences in the following example.

I wish to clarify an optimal approach if any of the two or another suggestion.

const Fraction & Fraction::timesEq(const Fraction & f) {

  //First approach
  numerator *= f.numerator;
  denominator *= f.denominator;

  //Second approach
  numerator *= f.getNumerator();
  denominator *= f.getDenominator();

  return (*this); //would 'return' statement this be considered best practice?
}

Solution

  • The second approach survives subclassing and possible virtual redifinitions of the methods if this matters for the particular case but more cumbersome and boring.