How do you copy contents from one object to another ? That's what we'll cover in this page. Before we march ahead let's review a few key concepts essential to our understanding of how an object is created and referenced.
Handle and Instance
A class variable such as pkt below is only a name by which that object is known. It can hold the handle to an object of class Packet, but until assigned with something it is always null. At this point, the class object does not exist yet.
class Packet;int count;endclass
Packet pkt;// pkt is pointing to null
An instance of that class is created only when it's new() function is invoked. To reference that particular object again, we need to assign it's handle to a variable of type Packet.
pkt =new();// or
pkt =new;// Also legal
So, if we declare another variable pkt2, it will point to null initially. Let's assign the handle pkt to the new variable pkt2 as follows.
pkt2 = pkt;
Now we have two handles, pkt and pkt2 pointing to the same instance of the class type Packet. This is because we did not create a new instance for pkt2 and instead only assigned a handle to the instance pointed to by pkt.