#827 – Making a Deep Copy with a Copy Constructor
April 22, 2013 2 Comments
The semantics that you use within a copy constructor can be to make a shallow copy of an object or a deep copy.
In the example below, the copy constructor for Dog makes a deep copy of the object passed in. In this case, that means that the new Dog that is created will also have a new instance of DogCollar object, copied from the DogCollar property of the original Dog object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class Dog { public string Name { get ; set ; } public int Age { get ; set ; } public DogCollar Collar { get ; set ; } // Constructor that takes individual property values public Dog( string name, int age) { Name = name; Age = age; } // Copy constructor (deep copy) public Dog(Dog otherDog) { Name = otherDog.Name; Age = otherDog.Age; Collar = (otherDog.Collar != null ) ? new DogCollar(otherDog.Collar.Length, otherDog.Collar.Width) : null ; } } |