Advertisement
pulchroxloom

A.h

Jan 29th, 2021
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #ifndef A_H
  2. #define A_H
  3.  
  4. #include <iostream>
  5.  
  6. class A {
  7.     int* a;
  8.     public:
  9.         A() : a(NULL) {
  10.             std::cout << "Called Default Constructor" << std::endl;
  11.             a = new int(10);
  12.         }
  13.         ~A() {
  14.             std::cout << "Called Destructor" << std::endl;
  15.             delete a;
  16.         }
  17.         A(const A& other) : a(NULL) {
  18.             std::cout << "Called Copy Constructor" << std::endl;
  19.             a = new int(*(other.a));
  20.         }
  21.         A(A&& old) : a(NULL) {
  22.             std::cout << "Called Move Constructor" << std::endl;
  23.             a = old.a;
  24.             old.a = NULL;
  25.         }
  26.         A& operator=(const A& other) {
  27.             // Self Assignment:
  28.             // int a = rand();
  29.             // a = a; // This is self assignment
  30.             if(this != &other) {
  31.                 std::cout << "Called Copy Assignment" << std::endl;
  32.                 delete a;
  33.                 a = new int(*(other.a));
  34.             }
  35.             return *this; // This is standard
  36.             // int a = rand();
  37.             // int b, c;
  38.             // c = b = a;
  39.         }
  40.         A& operator=(A&& old) {
  41.             if(this != &old) {
  42.                 std::cout << "Called Move Assignment" << std::endl;
  43.                 delete a;
  44.                 a = old.a;
  45.                 old.a = NULL;
  46.             }
  47.             return *this;
  48.         }
  49.         friend std::ostream& operator<<(std::ostream& os, const A& obj);
  50. };
  51.  
  52. std::ostream& operator<<(std::ostream& os, const A& obj) {
  53.     return os << obj.a << "   " << *(obj.a);
  54. }
  55.  
  56. #endif
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement