1 / 0

Class DynArray and Templates

Class DynArray and Templates. CS 1037a -- Topic 3. Related materials. Sec. 6.1-6.2: Templated functions and classes. from Main and Savitch “Data Structures & other objects using C++”. from CS1037 labs. Lab 3 , uses class DynArray. Remember “ DynArray ” for char ’s. in main().

sanjiv
Télécharger la présentation

Class DynArray and Templates

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Class DynArrayand Templates

    CS 1037a -- Topic 3
  2. Related materials Sec. 6.1-6.2: Templated functions and classes from Main and Savitch “Data Structures & other objects using C++” from CS1037 labs Lab3, usesclassDynArray
  3. Remember “DynArray” for char’s in main() inside DynArray.h DynArray a(3); a[0]=‘c’; a[1]=‘a’; a[2] =‘t’; classDynArray { public: DynArray(int w); ~DynArray(); char& operator[ ](int x); private: intm_size; char * m_container; } call stack heap DynArray::DynArray(intw) { m_size = w; m_container = newchar[w]; } DynArray ::~ DynArray() { delete [ ] m_container; } char& DynArray :: operator[ ](int x) { returnm_container[x]; } ‘c’ ‘a’ ‘t’ 3 a 2-3 inside DynArray.cpp
  4. Remember “DynArray” for char’s in main() inside DynArrayChar.h DynArrayChar a(3); a[0]=‘c’; a[1]=‘a’; a[2] =‘t’; classDynArrayChar { public: DynArrayChar(int w); ~DynArrayChar(); char& operator[ ](int x); private: intm_size; char * m_container; } To avoid confusion, we will rename char-based class to DynArrayChar To store other types of values one must define different classes like DynArrayInt or DynArrayFloat DynArrayChar::DynArrayChar(intw) { m_size = w; m_container = newchar[w]; } DynArrayChar ::~ DynArrayChar() { delete [ ] m_container; } char& DynArrayChar :: operator[ ](int x) { returnm_container[x]; } 2-4 inside DynArrayChar.cpp
  5. DynArrayof float Code for class DynArrayFloat would be almost identical to the code for class DynArrayChar, except for a few minor modifications: NameDynArrayChar must be replaced by a different class name, e.g. DynArrayFloat, throughout Return value for operator[ ] is of type float&; m_containerpoints to an array of float; constructors must reflect this change when dynamically allocating arrays to hold data
  6. DynArrayof Objects Let’s try to “generalize” the approach used with char data to build DynArrayof any class of objects... We will also implement a couple of improvements
  7. DynArrayItems.h short for unsigned int
  8. DynArrayItems.cpp default constructor is used for each item in the array
  9. DynArrayItems.cpp default constructor is used for each item in the array
  10. Static Allocation of a DynArray DynArrayItemsb(5); Call stack Heap Each array location holds an object of type Item b 5 m_size m_container ? ? ? ? ?
  11. Dynamic Allocation of a DynArray DynArrayItems *ptr= new DynArrayItems(5); Call stack Heap ptr 5 m_size The DynArrayobject and the container array are both in heap memory m_container ? ? ? ? ?
  12. Problems with DynArrayItemsClass If we need DynArraysfor 2 different kinds of objects in the same program, we will need to code 2 nearly identical classes requires copying code around changing code becomes a headache It would be great if we could write the DynArray code once, and let C++ generate slightly different classes for the type of data to be stored in each DynArrayInt A(20); DynArrayRect B(30);
  13. Problem Solution: Templates A C++ template class is a blueprint or a prototype for a family of classes Example: A template class for DynArrays: The template class defines a DynArrayof elements once, in a general way Programs using DynArrayscan then instantiate separate DynArrayclasses for as many specific types of elements as necessary
  14. Problem Solution: Templates When DynArrayobject is instantiated, the type of elements it stores MUST be specified If specialized DynArrayclassfor that specific type of elements does not already exist, the class is instantiated at compile time from a template Then, DynArrayobject of that class can be created by compiler
  15. Problem Solution: Templates Template class is declared in a .hfile In cs1037, we will put code for member functions into a .templatefile (for analogy with .cppfiles) - this is different from a generally used practice to keep all implementations for template class member functions in .h file.
  16. DynArrayWith and Without Templates // DynArrayItems.h // DynArray.h(template class)
  17. DynArrayWith and Without Templates Differences between .template, .cpp files: Occurrences of DynArrayItems:: are replaced by DynArray<Item> :: Code for each member function is preceded by template<class Item> Constructors are DynArray and destructor is ~DynArray
  18. DynArrayWith and Without Templates // DynArrayItems.cpp // DynArray.template
  19. DynArrayWith and Without Templates // DynArrayItems.cpp // DynArray.template
  20. DynArrayWith and Without Templates // DynArrayItems.cpp // DynArray.template
  21. DynArrayWith and Without Templates // DynArrayItems.cpp // DynArray.template
  22. Using DynArrayObjects DynArray objects now have to be declared as DynArray<int> b(20); or DynArray<char> c(5); Classes DynArray<int> andDynArray<char> are instantiated from the same template using different template parameter “Item” (int and char). Onlyint can be stored in DynArray object b, and only char can be stored in DynArray object c Member functions/operators can be used normally value of b[3]are always of type int value of c[2] are always of type char can call member functions like b.getSize() or c.getSize()
  23. Usage: DynArrayItemversus DynArray<Item> Outside the class definition, DynArrayItemas a type name is changed to DynArray<Item> Rule holds even in the portion of the .h file where prototypes of non-member functions are declared; each of these prototypes is preceded by the prefix template <class Item> In DynArray.template, constructor and destructor names are still DynArray, ~DynArray
  24. DynArray of Pointers to Objects Using template DynArray<Item> we can create arrays for storing any type of Items In particular, we can store pointers, e.g. DynArray<Rect *> b(20); DynArray<ImageCard *> c(10); Storing pointers to large objects instead of objects, may save a lot of memory and time (for copying these objects around)
  25. DynArray of Pointers to Objects (example) DynArray<int *> b(100 ); b[0] = new int(7); b[6] = new int(5); cout << b[6]; cout<< “size of DynArray b: ” << b.getSize( ) << endl; // 3
  26. DynArray of Pointers to Objects (example) DynArray<int *> *b = new DynArray<int*>(100 ); // dynamic DynArray (*b)[0] = new int(7); (*b)[6] = new int(5); cout << (*b)[6]; cout<< “size of DynArray b: ” << (*b).getSize( ) << endl; Parentheses around *b are needed in these calls; otherwise, C++ tries to execute the membership operator “.” first, before dereferencing. The call b->getSize(); is equivalent to (*b).getSize(); -> is often preferred by programmers: - it avoids operator precedence problems that result from forgetting to bracket the dereferencing operation
  27. Instantiating DynArrayObjects When DynArray<DynArray<int>> b(30); is first encountered: First, class DynArray<int> is instantiated Then, class DynArray<DynArray<int>> is instantiated Then the object b is instantiated (allocated) When DynArray<int> and DynArray<DynArray<int>> are encountered by compiler in later parts of code, the classes already exist
  28. Instantiating DynArrayObjects DynArray<int> b(40);// DynArray for 40int DynArray<char *> y(30);// DynArray for 30 pointers to char DynArray<Point> *p = new DynArray<Point>(60); //pholds the address of a dynamic DynArray for 60Point DynArray<Card*> *p = new DynArray<Card*>(20); //pholds the address of a dynamic DynArray for 20 pointers to Card DynArray< DynArray<float*> * > x(25); // DynArrayxholds 25pointers to DynArrayswhich hold pointers to float
  29. Some facts One can use any name-tag instead of Item in a definition of a template. E.g., these are identical templates MORE COMMON AMONG PROGRAMMERS
  30. Some facts One can define templates not only for classes, but also for functions or operators // in main()
  31. Some facts In general, one can define templates with any number of template parameters // in main()
  32. Exercise Write code for copy constructor and copy operator for template class DynArray<T> Overload templated global operator+ that combines the elements of twoDynArray<T> objects into one big array template <class T> DynArray<T> operator+ (const DynArray<T> & a, const DynArray<T> & b);
  33. BOTTOMLINE With templates we are ready to program general classes of data structures for arbitrary types of items/objects We can focus on general conceptual properties of different collections of data
More Related