Are the above points right? |
Yes. Although I'd re-write the final one as "Variables and objects of any kind should always be initialised." :)
Can a pointer to a data-type, declared/initialized inside a function or a class, be accessed outside of the function or class in which it was declared/initialized, as stated in the reply above: |
In this regard, you treat the pointer as any other variable which contains a number. You can pass it into a function, return it from a function, copy the value from one variable to another, etc.
If you're asking about the contents of the memory at the address that the pointer is set to, then that depends. If you dynamically allocate the memory on the heap, then that memory remains allocated until something in the code deletes it. However, if you choose to store the address of something else in that pointer, then you need to be aware of how long the data there is likely to remain valid.
Think back to the house analogy: if you buy some land and build a house on it, then you can give the address of the house to people, and you know that when they come looking for your house, they'll find it. You own that house, and you know that it'll be there as long as you want it to be.
If you write down the address of a house that somebody else has built on their land, then if you come back in 6 months, you might find that house still standing, or you might find that the owner's knocked it down and it no longer exists.
If you write down the address of a bit of land that someone's parked a mobile home on, you can be pretty sure that if you come back to that address in a few weeks, it won't be there any more.
The key thing is - just because you've written down the address, doesn't mean that the house will always be there. The paper won't magically burn up if the house is demolished. Nor will the house vanish just because you tear up the bit of paper with the address on it. And just because you write down an address on a bit of paper, it won't magically cause a house to build itself on that spot - someone needs to actually build it.
So it is with pointers. Your pointer might contain an address in memory, but you'll need to actually allocate and initialise the data at that address. You'll need to understand the circumstances under which that memory still contains the data you think is there, and the circumstances under which it will get thrown away.
One particular thing to be careful about is using pointers to objects on the stack, i.e. that have been declared and initialised in the normal way. When the object falls out of scope, the memory will be released and the data there will no longer be valid. If, however, you've kept the address of that object beyond this point, then don't attempt to try and access the data it points to - because it will be gone. The mobile home will have moved on, leaving an empty plot :)
Again, there will be plenty of material out there, online and in textbooks, that will explore this more thoroughly.