If we can instantiate an object of a class and access member methods then why a pointer to a class?
If you have just a base class and no derived classes, then it is good to create the object on the stack rather than pointer to the class. In the latter, you should be calling delete
on the pointer to return the resources acquired by new
. (Also make sure that stack never overflows. If you need large number of array of instances, then instantiate using new
is the only option.)
class foo
{
int a ;
};
foo obj1 ;
foo obj2 = obj1 ; // Copy construction. Both obj2, obj1 have it's independent
// copy of objects. (Deep copy)
foo *obj3 = new foo ;
foo *obj4 = obj3 ; // Copy construction. However, both obj3, obj4 point to the
// same object. (Shallow copy)
// You should be careful in this case because deletion of obj3
// makes obj4 dangling and vice versa.
Is there any benefit to it?
Polymorphism because it works only for pointers / references.
And when do we use a pointer to a class and when do we instantiate an object of it?
It depends on the requirement. As said earlier, if you have just a base class creation of object on stack is a better option.