I’ve a program which creates many instances of my own Class. Then I operate them: read, change, pass them to some third party methods etc.
There are three questions.
-
Do I store an vector of instances or a vector of pointers? Why?
-
If I do not want to change an instance do I pass to the function an instances or pointers to it? Why?
-
If I do want to change an instance, do I pass a pointer or a reference? Why?
Thanks in advance!
Class example:
class Player {
public:
static const char width = 35;
static const char height = 5;
static const char speed = 15;
int socketFD;
float xMin;
float xMax;
char status;
float x;
float y;
char direction;
Player ( int );
void Reset();
void Move();
void SetHost();
void SetClient();
private:
void EscapeCheck();
};
In case your object is big (i.e. more than 2-3 primitive types) you’d want to store a array of pointers to dynamically allocated instances. This will make reordering objects and resizing/reallocating the container much faster. If you are making use of polymorphism, you pretty much have to use pointers (note that references are also polymorphic) to the base class. This will prevent slicing, since all elements of an array must be the same size, so if you want to store multiple objects, pointers to the base class are the way to go.
The cases where you might prefer storing the instances in the container is if you have a single type (no inheritance and polymorphism) and it is not that big (i.e. a few primitive member types). For bigger objects you might want to use a linked list instead of an array, in order to avoid costly inserts and reallocations.
Pass a pointer to constant object or constant reference. Unless you are passing a primitive, where you can simply pass a cheap copy and avoid the modification of the original object.
Whether it is a pointer to const object or a const reference is up to your usage scenario, references are easier to work with, like with normal instances, but cannot be changed to reference to other objects as pointers can.
If you intend to change the instance, then pass either a pointer or a reference. Which one of the two – see above. This way you can directly modify the particular instance. You can also pass by value, but it will create one temporary copy, which you will later need to assign back to the original object. There is no point in doing that, and if modification is your intent, always go for pointers or references. Even if you don’t intend to modify an object, it is still much cheaper to pass a constant pointer or reference, since those are the size of an int, whereas the object might be significantly bigger, so there is no point copying it. If you are passing a primitive type, you might as well pass by value, although if you intend to modify the object, you still have one extra assignment which is avoidable.