adam smith
adam smith

Reputation: 35

How to initialize a heap allocated varible in the constructor

This is my "code":

class a{
    int *var=new int;
public:
    a(int i):*var(5){};
    ~a(){}
};

Now of course this doesn't work. How can I initialize a heap variable from the constructor? (I don't want to allocate the heap variable inside the constructor )

Upvotes: 1

Views: 1619

Answers (1)

Smeeheey
Smeeheey

Reputation: 10316

Like so:

class a{
    int *var;
public:
    a(int a):var(new int(5)){};
    ~a()
    {
        delete var;
    }
}

The memory allocation needs to happen in the constructor. Also, you need to make sure you deallocate in the destructor.

Note your parameter a to the constructor isn't used. If you mean this value to initialise your class variable a you should change your allocation call to new var(a).

Note 2: Unless you specifically need to manually manage memory (say for an exercise), a better design is to use smart pointers, such as:

class a{
    std::unique_ptr<int> var;
public:
    a(int a): var(std::make_unique<int>(5)){};
    ~a()
    {}
}

Upvotes: 4

Related Questions