Consider a class with just a single member for this example.
class tester
{
public:
    int tester_value;
    tester(){}
    tester(int test_val)
    {
      tester_value = test_val;
    } 
    
    tester(const tester & data) : tester_value(data.tester_value)
    {
      std::cout << "Copied!" << std::endl;
    }
};
I was curious as to the proper way to overload the = operator and why one way works and another does not.
For example, this operator overload does not seem to properly copy the data from one object to another.
Example 1:
tester operator=(const tester & data) const
{
  tester temp;    
  std::memcpy(&temp, &data, sizeof(tester));
  return temp;
}
However, this example works just fine.
Example 2:
tester& operator=(const tester & data)
{        
  tester_value = data.tester_value;
  return *this;
}
When using the following code to test each example...
  tester my_test = tester(15);
  
  tester my_second_test = tester(20);    
  
  my_test = my_second_test;
  
  std::cout << "my_test.tester_value:" << my_test.tester_value << std::endl;
  
  std::cout << "my_second_test.tester_value:" << my_second_test.tester_value << std::endl;
The result for example 1 will be:
15
20
While the result for example 2 will be:
20
20
So,
Question 1: Why is it that using a temporary variable and memcpy() does not work properly to copy the data from one object to another when overloading the = operator?
Question 2: What is the proper and most efficient way to do overload this operator?
I appreciate any explanation, I am still getting used to the C++ language.
Thanks in advance!
 
    