The three functions and operators in C++ overload of Boolan

  • 2020-05-17 05:57:26
  • OfStack

C++ 3 functions:

The destructor Copy constructor = operator (copy assignment operator)

If the programmer does not implement these three special member functions, the compiler will provide the default implementation.

Destructor:

If the object is created as a free variable, the destructor will be called when it is out of scope. If the object is created through the new operator, the destructor is called through the delete operator.

Copy constructor:

In the form of foo_t(const foo_t& foo), the copy constructor is called when:

When the object is returned by value (returned by value) Call the function that passes arguments by value (passed by value) Objects that are thrown by thrown or captured by caught The object is in an initialization list surrounded by ()

= operator:

Overloading = operator, such as foo_t& operator=(const foo_t& foo), which is called by assignment to an existing object (uninitialized object members call the copy constructor).

Here is an example of the code:


#include <cstring>
#include <iostream>
class foo_t {
 friend std::ostream &operator<<(std::ostream &os, foo_t const &foo) {
  os << foo.data;
  return os;
 }
 public:
 foo_t(void) : data(new char[14]) { std::strcpy(data, "Hello, World!"); }
 ~foo_t(void) { delete[] data; }
 foo_t(const foo_t& other);
 foo_t &operator=(const foo_t& other);
 private:
 char *data;
};
foo_t::foo_t(const foo_t& other) {
 std::cout << "call copy constructor!!!" << std::endl;
 this->data = new char[strlen(other.data) + 1];
 strcpy(this->data, other.data);
}
foo_t& foo_t::operator=(const foo_t& other) {
 std::cout << "call the copy assignment operator!!!" << std::endl;
 if (this == &other)
   return *this;
 this->data = new char[strlen(other.data) + 1];
 strcpy(this->data, other.data);
 return *this;
}
int main() {
 foo_t foo;
 std::cout << foo << '\n';
 foo_t t(foo);
 // foo_t t2 = t;
 foo_t t3;
 t3 = t;
 return 0;
}

To facilitate testing, you can set breakpoints at destructors, copy constructs, and = overloads, respectively, and watch the program execute.


Related articles: