Copy Constructors and Assignment Operator, When should I use?
Hi, all:
I know this is a basic concept but I still need some clearification.
It gave me a hard time
I read something says "Don't write a copy constructor if shallow
copies are ok" and "If you need a copy constructor, you also need a
destructor and operator="
My understanding, the shallow copy work for class that with int,
float ...etc internal datatype only. If I have pointers or vectors, is
that means I need to write my Copy Constructor/Operation operator.
Nothing clearer than an example.
Let's say I have a class:
Class ItemSet{
ItemListA a;
ItemListB b;
load() // call ItemListA.load(), call ItemListB.load()
}
Class ItemListA{
struct ItemA{
int aInt;
std::string aString;
} ;
std::vector <ItemA> m_vecA;
void load(); //function for populate m_vecA
ItemA FindItem(){
ItemA ia;
return ia
}
}
Class ItemListB{
struct ItemB{
int bInt;
std::string bString;
time_t: bTime;
} ;
std::vector <ItemB> m_vecB;
load(); //function for populate m_vecB
}
----------------------------------
Now Can I do:
ItemSet set1;
set1.Load();
ItemSet set2;
set2 = set1
? without create copy constructors for ItemSet class?
If I need to create copy constructor for ItemSet class, since
ItemListA and ItemListB is in ItemSet, I also need to create copy
constructor for these 2 classes, right/
-----------------------------
Also, if I need to create the copy constructor /overwrite assignment
operator for Item:
why does the function in ItemListA which returns struct ItemA work? Is
the return COPY the ItemA ?
Thanks a lot
-rockdale