Vino
Vino

Reputation: 2311

Is it okay to instantiate an object in the heap because of the following reason?

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

Answers (3)

Ron
Ron

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

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

As Dietmar remarked, use a member initializer list:

class SuperEntity
{
    Entity entity_;

public:
    SuperEntity( int value )
        : entity_{ value }
    {}
};

Upvotes: 4

R Sahu
R Sahu

Reputation: 206617

It is ok per the language but not necessarily the best pratice.

  1. Use an object if you can.
  2. Failing that, use a smart pointer instead of a raw pointer. See std::shared_ptr and std::unique_ptr.
  3. If you must use a raw pointer, make sure to follow The Rule of Three.

Upvotes: 4

Related Questions