Suppose I have defined a class called Entity
which has a data member which is a pointer to int. So for example
class Entity {
public:
int* ptr;
// other stuff
};
Is there a way to give the type int*
a constructor which takes an Entity
object? If I have an Entity object called my_entity
, I'd like to be able to do something like this
int* p(my_entity);
or this
int* p = my_entity;
which would require the compiler implicitly call a constructor for int*
that takes an Entity
.
Is this possible? (I know I could define a public get_pointer()
method in the Entity class and do something like int* p = my_entity.get_pointer();
but this seems clunky.)
Well, there is no constructor for a basic pointer - in the sense that there is no function implicitly called in order to initialise the pointer.
The closest you can come is to use a user-defined conversion operator function
There are variants of this, depending on what form of
const
qualification is needed (e.g. if the operator function doesn't change the object it acts on, it should beconst
and may be defined asoperator const int *()
).It is necessary to ensure that the pointer returned by the operator function is treated appropriately. If the user defined operator function returns a member of
some_entity
, it cannot be used oncesome_entity
ceases to exist. Similarly, if it uses dynamic memory allocation (e.g. return the result of anew
expression) the caller must explicitly release that memory to avoid a memory leak.