C++/when to use pointers & Referencs
Hi vijayan ,
I have some basic questions. I have worked in java for 1 year.Now i moved to C++, Here i am getting doubt when i have to use pointers and references.
1. When i have to create pointer object and noraml object
2.When iam designing a class on what basis in class i have to write pointer varibles and normal variables
3. when i have to use references? funtcion returns pointers and references?
Since up to now i worked on java .. iam getting doubts on these in C++. In none of the books didnt explained when we have to use pointers and references .
if possible can u plz explain with examples ?
Thanks in advance
When i have to create pointer object and normal object?
Use a normal (named) object in all situations where you do not want to manage the life time of the object programmatically and the object is of a non-polymorphic type. Use an anonymous object accessed via a pointer when you want the object to be of a dynamic storage duration - ie created with a new and destroyed by a delete or when the object is polymorphic. The common scenario in C++ is to have polymorphic objects, accessed via a base class to use pointer semantics.
When i am designing a class on what basis in class i have to write pointer variables and normal variables?
If a member of a class is 'owned' by the object of that class - it is created when the object is created, destroyed when the object is destroyed, and belongs only to this object, and will never change during the lifetime of this object - use a normal variable. If the object is shared, is polymorphic, or has a lifetime independent of the containing object, use a pointer variable.
when i have to use references? funtction returns pointers and references?
In general, for functions, prefer using references, unless the variable is always accessed using a pointer. Pass parameters of user defined types to functions by (const if non-modifiable) references where ever possible. If the lifetime of the object returned is over when the function exits, return by value. Otherwise, return by reference if it was not created using a new, by pointer if it was created via a new.
For some additional information and code snippets, see:
- look at section 3.3.1
Here is a somewhat more advance treatment, which also deal with many issues which are arcane to beginners. Don't try to read it all at one go, or be discouraged if you do not understand all of it. Take it in small chunks, and go back to it from time to time.