Well, by default a constructor gets called whenever an object is created. But is the same applicable when we create a pointer to an object?
I do not see a call to constructor when I create a pointer.
class* obj; //No call to constructor.
When we allocate dynamic memory to a pointer, new operator automatically calls the constructor. But what if we don't allocate memory? It is still a pointer to the class object . Shouldn't the constructor be called for it?
Could somebody please explain? Thanks in advance.
However, when are creating a pointer, you are NOT creating an actual object. If you don't initialize it, it will be pointing to garbage and dereferencing it will be an error.
Remember that just because you make a pointer does not mean it is pointing to anything.
If you just create a pointer without initializing it, the pointer points to a garbage address. It is supposed to be a pointer to a certain type of object, but that object does not exist.
There are a number of other ways you could end up in this situation. If you have an array of 10 objects and add 10 to the pointer to the first element, you will get a pointer that does not point to a valid object. Also, if you delete a pointer with dynamically allocated memory, the pointer value is not changed even though the object has disappeared.
A pointer does not refer to any object until you provide it with an address; therefore, no constructor is called. In order to optimize machine code slightly, these pointers do not default to NULL, and if you try to use the pointer for anything at all, your program will probably crash.
In case you still don't get it, ask yourself where the new object is supposed to be. If you assign the pointer the address of a local variable, it is on the stack. If you use new, it is on the heap. Where would the object be located before you initialize the pointer? None of the possible storage spaces (heap, stack, or global) would be suitable for that, thus there can be no object.
@firedraco - You said EXACTLY what I needed to understand. While creating a pointer , I am not creating an actual object and just creating a pointer of specific type does not mean it is pointing to anything unless you initialize it. I knew these things but I somehow gets confused when it comes to pointers. Thanks a lot for the share :)
@Telion - Thanks for the clarification. Now I have a clear image of how it works. However, I din't get the point
//Also, if you delete a pointer with dynamically allocated memory, the pointer value is not changed even though the object has disappeared.
Could you please elucidate? Does it mean once you assign a value to a pointer and after you delete the memory, the pointer will still be pointing to the same value? I do not see that happening. (which is logical. once freed, pointer will point to a garbage value). Or did I take your sentence in a wrong way?