Copy Constructor and member pointers - Beginner Q.
-
Hello, I need to write a copy constructor and my class has got a couple of member variables which are pointers. What I need is some general advise on how to write a copy constructor so, that I don't have bad hockey afterwards. Thanks very much! Matthias
-
Hello, I need to write a copy constructor and my class has got a couple of member variables which are pointers. What I need is some general advise on how to write a copy constructor so, that I don't have bad hockey afterwards. Thanks very much! Matthias
Hi, I would suggest that all classes your class has pointer members to, does also have copy constructors. That way you will keep your copy constructor tidy: Example: class CExClass { ... CExClass(const CExClass& Src) ... CAnyMember* m_pAnyMember; } CExClass::CExClass(const CExClass& Src) { m_pAnyMember = new CAnyMember(*Src.m_pAnyMember); } CAnyMember::CAnyMember(const CAnyMember& Src) { // copy ... } If you don`t want to make real copies of your data, you can use smartpointers as members instead of real pointers. Michael
-
Hi, I would suggest that all classes your class has pointer members to, does also have copy constructors. That way you will keep your copy constructor tidy: Example: class CExClass { ... CExClass(const CExClass& Src) ... CAnyMember* m_pAnyMember; } CExClass::CExClass(const CExClass& Src) { m_pAnyMember = new CAnyMember(*Src.m_pAnyMember); } CAnyMember::CAnyMember(const CAnyMember& Src) { // copy ... } If you don`t want to make real copies of your data, you can use smartpointers as members instead of real pointers. Michael
thx.