1 / 27

# Dynamic Data, Shallow Copies, and Deep Copies

Dynamic Data, Shallow Copies, and Deep Copies. Problem. Consider the following program that creates a grade tree makes a copy of the tree to save modifies the original tree. #include “stutree.h” int main() { Gradetree mygrades; // list of my grades

Télécharger la présentation

## Dynamic Data, Shallow Copies, and Deep Copies

E N D

### Presentation Transcript

1. Dynamic Data, Shallow Copies, and Deep Copies

2. Problem • Consider the following program that • creates a grade tree • makes a copy of the tree to save • modifies the original tree

14. Problem • Consider the following program that • creates a grade tree • calls a function, passing the grade tree by value • modifies the copy of the tree passed to the function • returns to the main function

21. Solution • We need deep copies in the two previous situations • A deep copy is a copy of not only the private root pointer, but also a copy of all of the dynamic data, i.e., a copy of all nodes in the entire tree • Can you think of other classes we have used that needed deep copies? • any class using linked lists (files gradelnklist, stackll, queuell)

22. Solution (continued) • Add a function to the Gradetree class that makes a deep copy when the assignment operator is used • This is a function that overloads the assignment operator, i.e., the = sign. • I actually already included this function in the Gradetree class

23. Solution (continued) • Add a function to the Gradetree class that makes a deep copy when the class is passed by value to a function • This is a function called a copy constructor. • The copy constructor is called when a class is passed by value. • I actually already included this function in the Gradetree class

24. stutree.h class Gradetree { public: // default constructor Gradetree (); // copy constructor - for deep copies Gradetree (const Gradetree& othergradetree); // destructor ~Gradetree (); // overload assignment for deep copies void operator= (const Gradetree& othergradetree); . . . private: Treenode* copytree (Treenode* t); // used by copy constructor and operator= void destroytree (Treenode* t); // used by destructor . . . Treenode* root; };