Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Instances VS pointers VS references

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.

  1. Do I store an vector of instances or a vector of pointers? Why?

  2. If I do not want to change an instance do I pass to the function an instances or pointers to it? Why?

  3. 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();
};
like image 755
Kolyunya Avatar asked Dec 02 '22 21:12

Kolyunya


1 Answers

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.

like image 78
Luchian Grigore Avatar answered Dec 04 '22 10:12

Luchian Grigore