Friday, August 14, 2009

Difference between C++ references and Java references

Many people who learn Java with a background of C++ often get confused between reference of C++ and reference of Java. Even if they share same phrase there is not much similarity between them. You might wonder that C++ pointers share the similar functionality that of Java references.
Here is the similarity between C++ pointers and Java references.



C++ PointersJava references
Declaration and assignment:
Obj* o1;//Uptil now no memory is allocated on heap
o1=new Obj();//Now we have o1 pointing to object on heap
Declaration and assignment:Obj o1;//Uptil now no memory is allocated
o1=new Obj();//Now we have o1 pointing to object on heap
Base class pointer can point to derived class objectBase claas reference pointes to derived class object
Obj* o1,o2; o1=new Obj();
o2=o1;
o1 and o2 now point to same object
Obj o1,o2; o1=new Obj();
o2=o1;
o1 and o2 now point to same object


In C++ if we try to assign derived class object to base class reference, object slicing will occur.
From this you can get a idea about how much strong the references are, they allow runtime polymorphism without dealing with pointers. In case of pointers you need to free the memory allocated for pointers. In Java we do not need to wory about freeing allocated memory because system(JVM) takes care of it. So Java tried to achive best of both the worlds. This all comes at the price. As garbage collection ( name of background thread responsible for releasing allocated memory ) run as a background process it slows down the system.

No comments:

Post a Comment