In this article, we will discuss vector of pointers to objects.
Object can be a class object or structure object.
Vector of Pointers to Structure
First, we will discuss vector of pointer to a structure.
Consider the structure,
struct obj{
int n;
int nsq;
};
The structure obj contains 2 variables – n and nsq. n is a integer and nsq is square of n.
Now, we will declare a vector of pointers of type obj,
vector<obj*> v;
The vector v stores the address of objects of type obj.
To push data in the vector, we first initialize a pointer of obj and push the pointer to the vector.
obj *newObj = new obj();
newObj->n = n;
newObj->nsq = n*n;
v.push_back( newObj );
Example,
#include<iostream>
#include<vector>
using namespace std;
struct obj{
int n;
int nsq;
};
int main() {
vector<obj*> v;
int n = 9;
for(int i=1;i<=n;++i){
obj *newObj = new obj();
newObj->n = i;
newObj->nsq = i*i;
v.push_back(newObj);
}
for(int i=0;i<v.size();++i){
cout<<"N = "<<v[i]->n<<" N*N = "<<v[i]->nsq<<endl;
}
}

Vector of Pointers to Class
The pointer to class works exactly the same as pointer to structure.
Consider the class,
class obj{
public:
int n;
int nsq;
obj(int n){
this->n = n;
this->nsq = n*n;
}
};
The class obj has 2 public members – n and nsq. n is an integer and nsq is square of n. The class obj has a constructor that initializes n and nsq.
We can push data to vector of class in same way as structure. First we initialize obj pointer using the constructor then push the pointer to the vector.
obj *newObj = new obj(n);
v.push_back( newObj );
Also, even with pointers we can only access the public members of the class.
Example,
#include<iostream>
#include<vector>
using namespace std;
class obj{
public:
int n;
int nsq;
obj(int n){
this->n = n;
this->nsq = n*n;
}
};
int main() {
vector<obj*> v;
int n = 9;
for(int i=1;i<=n;++i){
obj *newObj = new obj(i);
v.push_back(newObj);
}
for(int i=0;i<v.size();++i){
cout<<"N = "<<v[i]->n<<" N*N = "<<v[i]->nsq<<endl;
}
}

References