Monday, 10 April 2017

Basic OOP: Constructor, Class handle and class object

Every class has in built method called: new (known as constructor).

Let's see an example,

class packet;
  int val;
endclass: packet

When we take the instance of this calss,

packet pkt; // This is just the variable of the data type packet.

We can not directly use this pkt to access the packet class property. We have to construct,

pkt = new; // This class variable is now class object.

Object can only be created if we call new of the class variable. Ultimately, class object is the class variable with it's dedicated memory. So whenever we call constructor of the class variable, memory is getting allocated for that class variable and it's memory pointer (known as class handle) is stored inside the class variable.

User can also overwrite this constructor,

class packet;
...
function new (int _val_);
  val = _val_;
endfunction
endclass

packet pkt = new(5);


Example:

Packet pkt1, pkt2;

pkt1 = new();


 _____________
|___0x80______|
|   int val             |
|_____________|

pkt2 = new();
 _____________
|___0x84______|
|   int val             |
|_____________|

pkt1 = new();
 _____________
|___0x88______|
|   int val             |
|_____________|
 _____________
|___0x80______|
|   Unused           |
|_____________|

pkt2 = pkt1;
 _____________
|___0x88______|
|   int val             |
|_____________|
 _____________
|___0x84______|
|   Unused           |
|_____________|

Now both pkt2 and pkt1 both are variables are pointing to the same memory (0x84). Because
pkt2 = pkt1 copies memory pointer only.

pkt1 = new();

 _____________
|___0x90______|
|   int val             |
|_____________|   // For pkt1
 _____________
|___0x88______|
|   int val             |
|_____________|  // For pkt2

pkt2 = null;
 _____________
|___0x90______|
|   int val             |
|_____________|   // For pkt1
 _____________
|___0x88______|
|   Unused           |
|_____________| 




No comments:

Post a Comment