1
    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?

  • possible duplicate of [How to initialize a vector of pointers](http://stackoverflow.com/questions/9090680/how-to-initialize-a-vector-of-pointers) – Mureinik Jun 10 '15 at 05:16
  • 1
    Er... How do you *want* to intialize it? What do you want to obtain as the end result of the initialization? How do you expect to receive any advice, if you don't specify what exactly you are trying to do? – AnT stands with Russia Jun 10 '15 at 05:47

3 Answers3

4

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.

Phil Miller
  • 36,389
  • 13
  • 67
  • 90
1

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

bazz-dee
  • 687
  • 5
  • 23
1

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
Andreas DM
  • 10,685
  • 6
  • 35
  • 62