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();
};
Do I store an array of instances or an array of pointers? Why?
If Class
is a base class, and you want to prevent object slicing, you store pointers. Otherwise, objects.
If i do not want to change an instance do I pass to the function an instances or pointers to it? Why?
If you pass by value, you don't modify the original object because you're working on a copy. If you pass a pointer or a reference, you mark it as const:
void foo ( MyClass const* );
void foo ( MyClass const& );
If i do want to change an instance, do i pass a pointer or a reference? Why?
Either. I personally prefer references, pointers are more tightly connected to dynamic allocation.
Nowadays, RAII is often used, so an excellent alternative is to use smart pointers instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With