I want to design a class in C++ called Entity. That entity has a pointer to a member of Vector3D which is the position of the entity in 3D space. The constructor allows a pointer of type Vector3D to be passed to the constructor, such that the Vector3D instance is instantiated outside of the class.
Because there is a pointer to a dynamically allocated object, the copy constructor and assignment operator must be overloaded to deep copy the vector. However, because the vector can be passed in the constructor, it may also be used elsewhere and so cannot be deleted in the destructor. But if a new Entity created through the copy constructor or assigned with the = operator, the entity class must delete the instance of vector because it was instantiated within the Entity class.
What is the best way to solve such problems?
#ifndef ENTITY_H
#define ENTITY_H
#include "Vector3D.h"
class Entity {
public:
Entity(Vector3D*);
Entity(const Entity&);
~Entity();
Entity& operator = (const Entity&);
protected:
Vector3D* vector;
};
#endif