int* ptr1 = new int;
int* ptr2 = new int;
*ptr2 = 44; //assign 44 to "value pointed by ptr2"
*ptr1 = *ptr2; //*ptr = 44
delete ptr1; //delete ptr1
ptr1 = ptr2; //make ptr1 point to same address as ptr2
delete ptr2; //delete ptr2
ptr1 = NULL; //prevent dangling pointer
cin.get();
return 0;
//*******************************************************
//Example of DEEP COPY
//COPY A CLASS OBJECT WITH ITS POINTERS
//*******************************************************
class Message
{
public:
//output operation
void Print() const;
//DEEP COPY OPERATION
void CopyFrom( /* in */ Message otherMsg);
//Constructor
Message(/* in */ Time newTime,
/* in */ const char* msgStr);
//Copy-constructor
Message(const Message& otherMsg);
//Deconstructor
~Message();
private:
Time time;
char* msg;
}
//This is what happens in CopyFrom(Message otherMsg)
//This function is to copy an existing class object
//Already pointed to a dynamic data
void CopyFrom(/* in */ Message otherMsg)
{
//Copy variable
time = otherMsg.time;
//Deallocate original
delete [] msg;
//Allocate new array
msg = new char[strlen(otherMsg.msg) + 1]
//Copy the chars
strcpy(msg, otherMsg.msg);
}
//This is what happens in Message(const Message& otherMsg0
//This copy constructor will create a new class object
Message(const Message& otherMsg)
{
//copy variable
time = otherMsg.time;
//Allocate new array
msg = new char[strlen(otherMsg.msg) + 1];
//copy
strcpy(msg, otherMsg.msg);
}
//*******************************************************