You are failing to understand pointers.
Look at your default constructor:
1 2 3 4 5 6 7 8 9 10
|
DynamicInt::DynamicInt()
{
int z = 0;
ptr = &z; //set the dynamic data member to zero
cout << "\n\naddress of z " << &z;
cout << "\nvalue of *ptr " << *ptr;
cout << "\nvalue of ptr " << ptr;
}
| |
Here's what's happening.
1) You're creating a local variable 'z' and assigning it to zero
2) You're assigning ptr to point to 'z'.
Note: this does not mean 'ptr' points to zero. Nor does it mean pointer is zero. It means pointer points to z.
The problem is, 'z' goes out of scope at the end of the function and gets destroyed, but 'ptr' still points to it, meaning 'ptr' becomes a bad pointer (ie: what it points to no longer exists, so it points to nothing / garbage memory)
This is bad bad bad bad.
Your other constructor has the same problem:
1 2 3 4 5 6 7 8
|
DynamicInt::DynamicInt(int m)
{
ptr = &m; //set the dynamic member data with m
cout << "\n\naddress of m " << &m;
cout << "\nvalue of *ptr " << *ptr;
cout << "\nvalue of ptr " << ptr;
}
| |
'm' is local to this ctor, so as soon as the ctor returns, 'm' no longer exists, which means 'ptr' no longer points to valid memory!
On the other hand, your copy ctor is correct. By allocating the memory with new, the memory you're pointing to exists until you delete it (ie: it does not get destroyed when the function exits).
But, since you're not deleteing the memory (your dtor has that commented out), you have memory leaks.
Also the assignment operator should return
DynamicInt&
not
DynamicInt
(ie, it should return a reference to *this, not a copy of *this)