The program above is an exercise involving the = operator and a pointer as a data member. When the = operator is used, new memory is allocated for the pointer in the assigned to class, and the value pointed to by the assigning class is stored in this heap memory, to avoid multiple objects pointing to the same place.Code:#include <iostream> using namespace std; class Point { private: int* ptr; public: Point(int val) {ptr = &val;} ~Point() {delete ptr;} void GetVal() const {cout << *ptr << endl;} void NewLoc(int loc) {delete ptr; ptr = &loc;} void SetVal(int val) {*ptr = val;} void printaddr() const {cout << ptr << endl;} int* GiveVal() const {return ptr;} const Point& operator=(const Point& rhs) { if(&rhs != this) { delete ptr; ptr = new int; *ptr = *(rhs.GiveVal()); } return *this; } }; int main() { int myInt = 90, yourInt = 50; Point p1(myInt), p2(yourInt); p1.GetVal(); p1.printaddr(); p2.printaddr(); //p2 = p1; p2.printaddr(); //cout << *(p2.GiveVal()) << endl; //cout << *(p1.GiveVal()) << endl; p2.GetVal(); p1.GetVal(); p2.SetVal(1267); p1.GetVal(); return 0; }
However, after the commented out line p2 = p1, the values pointed to by the pointers of both objects seem to change unaccountably, and I don't understand why. The other commented out lines seem to change the values further even though they are intended to fetch values... After this, p2's value is modified, and p1's value also changes, even though the two objects should now not be pointing to the same memory addresses!
The code is rather clumsy, for example there are several member functions that all do similar things, but these were implemented in an attempt to find out what was going wrong.
I would be very grateful if someone with more expertise could assist a bemused novice, and apologise for wasting your time if the mistake is glaringly obvious and simple.