It initializes an object by copying the state from another object of the same class. Whenever an object is copied, another object (the copy) is created, so a constructor is called (see FAQ 20.02). This constructor is called the copy constructor. If the class of the object being copied is X, the copy constructor's signature is usually X::X(const X&). One way to pronounce X(const X&) is X-X-ref (pretend the const is silent). The first X refers to the name of the member function, and the X-ref refers to the type of the parameter. Some people prefer the shorthand X-X-ref to the phrase copy constructor. In the following example, the copy constructor is MyString::MyString(const MyString&). Notice how it initializes the new MyString object to be a copy of the source MyString object. #include <new> #include <cstring> using namespace std; class MyString { public: MyString(const char* s) throw(bad_alloc); <-- 1 MyString(const MyString& source) throw(bad_alloc); <-- 2 ~MyString() throw(); <-- 3 MyString& operator= (const MyString& s) throw(bad_alloc); <-- 4 protected: unsigned len_; // ORDER DEPENDENCY; see FAQ 22.10 char* data_; }; MyString::MyString(const char* s) throw(bad_alloc) : len_(strlen(s)) , data_(new char[len_+1]) { memcpy(data_, s, len_+1); } MyString::MyString(const MyString& source) throw(bad_alloc) : len_(source.len_) , data_(new char[source.len_+1]) { memcpy(data_, source.data_, len_+1); } MyString::~MyString() throw() { delete[] data_; } int main() { MyString a = "xyzzy"; //Calls MyString::MyString(const char*) MyString b = a; //Calls MyString::MyString(const MyString&) }
|