For the below code, when v is copied, the members of Model class do not get copied.
#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
using namespace std;
class SomeNewClass
{
public:
int a;
};
class Model
{
public:
int i;
SomeNewClass* s;//A deep copy won't happen here automatically
Model() {}
Model(const Model& m):i(m.i)
{
cout<<"Model Copy ctor invoked"<<endl;
}
};
class ModelInherit : public Model
{
public:
int j;
ModelInherit() {}
ModelInherit(const ModelInherit& m):j(m.j)
{
//i=m.i;//I don't want to copy like this. I want the copy ctor of Model to be invoked
cout<<"ModelInherit Copy ctor invoked"<<endl;
}
};
int main()
{
boost::ptr_vector<ModelInherit> v;
v.push_back(new ModelInherit);
v[0].j = 10;
v[0].i = 20;
v[0].s = new SomeNewClass();
v[0].s->a = 99;
boost::ptr_vector<ModelInherit> v2( v );
cout<< v2[0].j <<endl;
cout<< v2[0].i <<endl;
//cout<< v2[0].s->a <<endl;//segmentation fault
}
What is important to note is that if you comment out the copy constructor of ModelInherit, then the pointer container automatically copies the i variable in the Model class. Sad part is that "SomeNewClass* s" does not get copied. No deep copy.
So my questions are:
- Do you know how to invoke the copy constructor of the Model class in the above code?
- How do I ensure a deep copy when the pointer container is automatically copying variables so that even the 'a' variable of SomeNewClass gets copied?