The Copy Constructor

From Appmethod Topics
Jump to: navigation, search

Go Up to Constructors Index

A copy constructor for class X is one that can be called with a single argument of type X as follows:

X::X(X&)

or

X::X(const X&)

or

X::X(const X&, int = 0)

Default arguments are also allowed in a copy constructor. Copy constructors are invoked when initializing a class object, typically when you declare with initialization by another class object:

X x1;
X x2 = x1;
X x3(x1);

The compiler generates a copy constructor for class X if one is needed and no other constructor has been defined in class X. The copy constructor that is generated by the compiler lets you safely start programming with simple data types. You need to make your own definition of the copy constructor if your program creates aggregate, complex types such as class, struct, and array types. The copy constructor is also called when you pass a class argument by value to a function.

See also the discussion of member-by-member class assignment. You should define the copy constructor if you overload the assignment operator.

See Also