deep copying

I'm having a problem with copying vectors. So I have this vector of objects call it std:: vector<parent*> first_vector. parent is the base class. The problem is I want to create a seperate vector std::vector<parent*> second_vector that gets all the information copied from first_vector.

The problem is when I copy it like this

 
second_vector = first_vector;


it copies only the adress of the pointers in first_vector so when I change one it changes the other. How do I deep copy vector with pointers such that they are independant? Let me know if I need to be more specific.

ps. these vectors contain a lot of information.
Last edited on
You need to do 2 things:

1) Use the clone pattern: http://www.cplusplus.com/forum/articles/18757/

2) Clone each element in the vector:

1
2
3
4
second_vector.resize(first_vector.size());

for(unsigned i = 0; i < first_vector.size(); ++i)
  second_vector[i] = first_vector[i]->clone();
here is the error i'm getting

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
c:\program files\microsoft visual studio 10.0\vc\include\sstream(724): error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files\microsoft visual studio 10.0\vc\include\ios(176) : see declaration of 'std::basic_ios<_Elem,_Traits>::basic_ios'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          This diagnostic occurred in the compiler generated function 'std::basic_stringstream<_Elem,_Traits,_Alloc>::basic_stringstream(const std::basic_stringstream<_Elem,_Traits,_Alloc> &)'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]


It is because the objects in my vector contain string stream
Are you trying to copy a private classed vector into a vector inside of a member that's not it's friend?
yes
C++ doesn't allow you to access (read or right) any private members without being either a friend, or having inheritance.

http://www.cplusplus.com/doc/tutorial/inheritance/

This will give you more information on friendship and inheritance.
I'm unsure of who needs to befriend who?
Topic archived. No new replies allowed.