Reputation: 2311
I have a class and the constructor accepts a parameter. For example,
class Entity
{
private:
int number_;
public:
Entity(int number):number_(number)
{
std::cout << "Entity object created";
}
}
// header
class SuperEntity
{
private:
Entity *entity_;
public:
SuperEntity(int value);
};
// source
SuperEntity::SuperEntity(int value)
{
entity_ = new Entity(value);
}
class SuperEntity
has a private member Entity
. Since in order to instantiate Entity
you need to pass in an int
to it's constructor and cannot be done the declaration file (superentity.h
) because the int
value needed to instantiate Entity
is not available yet, is it okay to dynamically allocate Entity
in SuperEntity
's constructor? Is this a bad practice? Thanks.
Upvotes: 1
Views: 87
Reputation: 15511
It's fine to have a pointer data field for a decoupled has-a relationship. If you really want to stick to pointers then you should prefer the std::unique_ptr to raw pointer and utilize the std::make_unique function in the member initializer list of the constructor:
class SuperEntity {
private:
std::unique_ptr<Entity> entity_;
public:
SuperEntity(int value);
};
SuperEntity::SuperEntity(int value)
: entity_(std::make_unique<Entity>(value))
{}
If you want to have a classic has-a relationship abstraction, namely a data field whose lifetime is bound to owners lifetime then loose the pointer and go with the object:
class SuperEntity {
private:
Entity entity_;
public:
SuperEntity(int value);
};
SuperEntity::SuperEntity(int value)
: entity_(value)
{}
};
The entity_
object will be destroyed once the object of type SuperEntity
goes out of scope.
Upvotes: 0
Reputation: 145279
As Dietmar remarked, use a member initializer list:
class SuperEntity
{
Entity entity_;
public:
SuperEntity( int value )
: entity_{ value }
{}
};
Upvotes: 4
Reputation: 206617
It is ok per the language but not necessarily the best pratice.
std::shared_ptr
and std::unique_ptr
.Upvotes: 4