Advertisement
Eiffel

Exercise 2/24

Feb 24th, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. //This code is not working as expected.
  2. //Fix the code and reply with your edited code.
  3. #include <iostream>
  4. using namespace std;
  5. class Line {
  6. public:
  7.     int getNum() const;
  8.     Line(int value); // overloaded constructor
  9.     Line(const Line &obj); // copy constructor
  10.     ~Line(); // destructor
  11.     Line &operator = (const Line& right) {
  12.         cout << "Assignment operator." << endl;
  13.             if (this != &right) {
  14.                 delete ptr;
  15.                 ptr = new int;
  16.                 *ptr = *right.ptr;
  17.             }
  18.             return *this;
  19.     }
  20. private:
  21.     int *ptr;
  22. };
  23.  
  24. // Member functions definitions
  25. Line::Line(int num) {
  26.     cout << "Overloaded constructor." << endl;
  27.     ptr = new int;
  28.     *ptr = num;
  29. }
  30. Line::Line(const Line &obj) {
  31.     cout << "Copy constructor." << endl;
  32.     ptr = new int;
  33.     *ptr = *obj.ptr; // copy the value
  34. }
  35. Line::~Line() {
  36.     cout << "Freeing memory!" << endl;
  37.     delete ptr;
  38.     ptr = nullptr;
  39. }
  40.  
  41. int Line::getNum() const {
  42.     return *ptr;
  43. }
  44. void displayNum(Line obj) {
  45.     cout << "value of num : " << obj.getNum() << endl;
  46. }
  47.  
  48. // Main function for the program
  49. int main() {
  50.     Line line1(10);
  51.     Line line2 = line1;
  52.     Line line3(30);
  53.     line3 = line2;
  54.     displayNum(line1);
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement