11.5
Copy Constructor - When Is It Used?
A copy constructor is called when ▪An object is initialized from an object of the same class ▪An object is passed by value to a function ▪An object is returned using a return statement from a function ▪▪Sphere basketball(4.5);▪Sphere collegeBBall(basketball);▪Sphere bigTenBBall = collegeBBall;▪bigTenBBall = basketball;
Copy Constructors
Special constructor used when a newly created object is initialized to the data of another object of same class
copy constructor example
class Address { private: string street; publ ic : } ; Address() {street=""; } Address(string st) { setStreet (st ); } void setStreet(str i ng st) {street = st; } string getStreet () const { return street ; } We could then create Mary's address and initialize Joan's address to a copy of Mary's using the following code: Address mary("123 Main St"); Address joan = mary;
default copy constructor
simply copies the data of the existing object to the new object using memberwise assignment
Copy Constructor, Memberwise Assignment, or neither?
▪▪Sphere basketball(4.5); ▪Sphere collegeBBall(basketball); ▪Sphere bigTenBBall = collegeBBall; ▪bigTenBBall = basketball;