0

A class T shall provide a member function that copies some but not all member variables (minimal example: just one variable X) from one object of type T to another object of type T. There are two possible solutions, copying from and copying to:

class T {
    some_type X;
    [...]
    void copy_X_from_other( const T& other ) { X = other.X; }
    void copy_X_to_other  ( T& other ) const { other.X = X; }
};

Are there reasons to prefer one variant over the other? Are there guide lines, best practice examples, or whatsoever?

How should the function be named? An ideal name would be much shorter than copy_(from|to)_other, yet leave no doubt about the direction of the copying.

Joachim W
  • 7,290
  • 5
  • 31
  • 59

1 Answers1

0

It is a pretty weird thing to try to copy just one property, but I am not one to question that.

Why not just do:

void copy_<property_name>( const T& other ) { <property_name> = other.get_<property_name>; }

This would follow the standard of copy assignment, which is defined as

T& operator=(const T& other)
{
    //copy
    //return
}

and as you can see, the receiving party is on the left in this as well.

Other than that, I don't think there's any standards for trying to copy just one property of another object.

  • Sorry, I have been misleading you by writing "one property", which is an extreme simplification of my real problem. I'll edit the question to make that clearer. – Joachim W Jan 07 '16 at 12:34
  • The solution still applies, just add more member variables, right ? Unless you want to select which member variables you want to copy, is that what you actually want to do ? – user1234141515134321321513 Jan 07 '16 at 12:55