1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

C++ will supply a copy constructor for each class that recursively copies member data from the source instance to the destination. However, if any of the class members are pointers, then this will give you two pointers to the same memory location. The copy constructor should be of type:

T( const T & )

That is, it is a constructor that can read but not modify (that's why the constis there) another instance of T. Here C++ passes the instance by reference for efficiency. For example:

class T {
char* p;
public:
T()
{};
// null constructor to make p
T( char* s )
{ p = strdup( s ); }
// a copy constructor
T( const T& u )
{ p = strdup( u.p ); }
// a better copier
~T()
{ delete p; }// the destructor }

22-Mar-98

Page 16

C201/TAM