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
class Entity
{
public:
operator int *();
};
Entity::operator int *()
{
// return something appropriate that is of type int *
}
// sample usage in a function somewhere
int *p = some_entity; // implicitly conversion that calls the operator int *()
int *another_p = static_cast<int *>(some_entity); // explicit conversion
int *yet_another_p = some_entity.operator int *();
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 be const
and may be defined as operator 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 once some_entity
ceases to exist. Similarly, if it uses dynamic memory allocation (e.g. return the result of a new
expression) the caller must explicitly release that memory to avoid a memory leak.