vector of class pointers initialization

2.9k views Asked by At
    class Comp
{
    //...
};

class MyClass
{
private:
    vector<Comp*>vec;
    //...
};

I need to initialize a vector of class type pointers to objects. how can I initialize it?

3

There are 3 answers

0
bazz-dee On

Use vec.push_back(new Comp()) but remember to delete all items using delete vec[<item>]

1
Phil Miller On

You can set an initial size (e.g. 10, as shown below), filled with all NULL values with the constructor:

vector<Comp*> vec(10, NULL);

You can also insert elements in various ways, using the push_back(), push_front(), and insert() methods.

0
Andreas DM On

The vector is private, I would have the constructor initialize it with the member initializer list:

class MyClass
{
public:
    MyClass();
private:
    vector<Comp*> vec;
};

MyClass::MyClass()
: vec(10, nullptr) // edit to suit the size and content.
{}                 // alternatively initialize it inside the body {} with loop