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

Copy constructors
C++ will call the copy constructor for class T when:

*An instance of class T is created from an existing
instance of class T.
For example:
*A function is called and an argument of class T is
passed by value:
*An unnamed temporary variable is created to hold the
instance of class T returned by some function.

class T {
char* p;
public:
T()
{};
// the null(default) constructor
T( char* s )
{ p = strdup( s ); }
~T()
{ delete p; }
};

T foo( T c ) // definition of function foo()
{ return c; };

int main() {
T* a = new T( "hello" );

T b;

// uses null constructor

T c = *a;// or T c(*a);
// copy constructor will be called for c
b = foo( *a );
// copy constructor will be called twice,
// once to pass a to foo, and once to set b
delete a;
// The string that b and c used is gone!

}

22-Mar-98

Page 15

C201/TAM