1/*
2 * Assignment operator overload in C++ is used to copy one object into another.
3 * Specifically, a 'deep' copy is made, such that any heap-allocated memory
4 * in the copied-from object is copied fresh to the copied-to object. Note also
5 * that the copied-to object ('this') must deallocated any of its own
6 * heap-allocated memory prior to making the copy.
7 *
8 * The assignment operator overload is called as follows:
9 *
10 * Array a;
11 * Array b;
12 * // ... put data in b / a ...
13 * a = b; // a now becomes a deep copy of b.
14 *
15 * See below for implementation details.
16 */
17
18/*
19 * Function: Example assignment operator overload for an Array class.
20 * Parameters: An Array to make a deep copy of
21 * Returns: A reference to the data in this (for chained assignment a = b = c)
22 * Effects: This is now a deep copy of other
23 */
24Array& Array::operator=(const Array& other) {
25 if (this != &other) { // ensure no self-assignment (i.e. a = a)
26 clear(); // deallocate any heap-allocated memory in 'this'
27 copy(other); // make a deep copy of all memory in 'other' to 'this'
28 }
29 return *this; // return the data in 'this'
30}
31
32/*
33 * Function: clear
34 * Parameters: None
35 * Returns: None
36 * Effects: Deallocates heap-allocated memory associated with this object.
37 */
38void Array::clear() { delete [] data; }
39
40/*
41 * Function: copy
42 * Parameters: An array to make a deep copy of
43 * Returns: None
44 * Effects: Makes a deep copy of other into this.
45 */
46void Array::copy(const Array& other) {
47 for (int = 0; i < other.len; i++) {
48 this->data[i] = other.data[i];
49 }
50 this->len = other.len;
51}
52
1// money.h -- define the prototype
2class Money
3{
4 public:
5 Money & operator += (const Money &rhs);
6}
7
8// money.cpp -- define the implementation
9Money& Money :: operator += (const Money &rhs)
10{
11 // Yadda Yadda
12
13 return *this;
14}
1#include <iostream>
2
3class ExampleClass {
4 public:
5 ExampleClass() {}
6 ExampleClass(int ex) {
7 example_ = 0;
8 }
9 int& example() { return example_; }
10 const int& example() const { return example_; }
11 //Overload the "+" Operator
12 ExampleClass operator+ (const ExampleClass& second_object_of_class) {
13 ExampleClass object_of_class;
14 object_of_class.example() = this -> example() + second_object_of_class.example();
15 return object_of_class;
16 }
17 private:
18 int example_;
19};
20
21int main() {
22 ExampleClass c1, c2;
23 c1.example() = 1;
24 c2.example() = 2;
25 ExampleClass c3 = c1 + c2;
26 //Calls operator+() of c1 with c2 as second_object_of_class
27 //c3 gets set to object_of_class
28 std::cout << c3.example();
29}