Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.07 KB | None | 0 0
  1. # Structures & Objects
  2.  
  3. * Built-in primitive types (`int, double, char`) are limiting: not everything is a number or character
  4. * Example: Lab 10: sorting teams
  5. * Encapsulation:
  6. 1. The grouping of data
  7. 2. The protection of data
  8. 3. The grouping of functionality that acts on that data
  9.  
  10. ## Encapsulation in C
  11.  
  12. * C only provides weak encapsulation, that is, #1 the grouping of data
  13. * C provides this through the use of structures
  14. * Syntax for declaring a structure:
  15.  
  16. ```c
  17. typedef struct {
  18. int year;
  19. int month;
  20. int day;
  21. } Date;
  22.  
  23. typedef struct {
  24. int nuid;
  25. char * firstName;
  26. char * lastName;
  27. Date dateOfBirth;
  28. double gpa;
  29. } Student;
  30. ```
  31.  
  32. * In general, structures are declared in a header file `.h`
  33. * Modern convention: use `UpperCamelCasing` for structure names, `lowerCamelCasing` for structure elements ("fields")
  34. * Semicolons delimit the fields in a structure
  35. * structures that use other structures must be declared after the structures they use
  36. * In general, all functions that use the structure are also included in the same header/source file (`student.h, student.c`)
  37.  
  38. ## Using Structures
  39.  
  40. * once a structure has been declared, you can use it like any other variable
  41. * The dot operator allows you to access individual fields in a structure
  42.  
  43. ```c
  44. Student s;
  45. s.nuid = 12345678;
  46. s.firstName = (char *) malloc(6 * sizeof(char));
  47. strcpy(s.firstName, "Chris");
  48. s.lastName = (char *) malloc(7 * sizeof(char));
  49. strcpy(s.lastName, "Bourke");
  50. s.gpa = 3.5;
  51. s.dateOfBirth.year = 1978;
  52. s.dateOfBirth.month = 7;
  53. s.dateOfBirth.day = 9;
  54. ```
  55. ## Factory Functions
  56.  
  57. * Writing a "factory" function allows you to create new structures easily
  58.  
  59. ```c
  60. /**
  61. * Returns a pointer to a newly constructed
  62. * student structure with the given values
  63. */
  64. Student * createStudent(int nuid,
  65. const char * firstName,
  66. const char * lastName,
  67. double gpa,
  68. Date dateOfBirth) {
  69. Student *s = NULL;
  70. s = (Student *) malloc(sizeof(Student) * 1);
  71. //you *could* dereference and then use the dot operator:
  72. //(*s).nuid = 123456878;
  73. s->nuid = nuid;
  74.  
  75. s->firstName = (char *) malloc( (strlen(firstName)+1) * sizeof(char));
  76. strcpy(s->firstName, firstName);
  77. s->lastName = (char *) malloc( (strlen(lastName)+1) * sizeof(char));
  78. strcpy(s->lastName, lastName);
  79. s->gpa = gpa;
  80.  
  81. s->dateOfBirth.year = dateOfBirth.year;
  82. s->dateOfBirth.month = dateOfBirth.month;
  83. s->dateOfBirth.day = dateOfBirth.day;
  84.  
  85. return s;
  86. }
  87.  
  88. ...
  89.  
  90. Date dayOfBirth;
  91. dayOfBirth.year = 1978;
  92. dayOfBirth.month = 7;
  93. dayOfBirth.day = 9;
  94. Student *me = createStudent(12345678, "Chris", "Bourke", 3.5, dayOfBirth);
  95.  
  96. Student *kyle = createStudent(87654321, "Kyle", "Schwarber", 3.95, TODO);
  97. ```
  98.  
  99. ### Using Structures in Arrays
  100.  
  101. * You can create static arrays of structures, but its better to create dynamic arrays
  102.  
  103. ```
  104. int n = 10;
  105. int *a = (int *) malloc(sizeof(int) * n);
  106. //create an array of Students:
  107. Student *roster = (Student *) malloc(sizeof(Student) * n);
  108. roster[0].nuid = 123455;
  109.  
  110. //this dereferences the returned Student pointer so that it can be assigned as the
  111. // first element in the array
  112. roster[0] = *createStudent(12345678, "Chris", "Bourke", 3.5, dayOfBirth);
  113.  
  114. //alternatively, you could have an array of Student pointers
  115. //a roster of 10 students
  116. Student **roster = NULL;
  117. roster = (Student **) malloc(sizeof(Student *) * 10);
  118. roster[0] = createStudent(12345678, "Chris", "Bourke", 3.5, dayOfBirth);
  119. ```
  120.  
  121. ### Passing Structures to functions
  122.  
  123. * Its always best to pass by reference
  124.  
  125. ```c
  126. /**
  127. * Prints the given Student structure to the standard
  128. * output
  129. */
  130. void printStudent(const Student *s) {
  131. //printf("%s, %s (%d) GPA = %.2f\n", s->lastName, s->firstName, s->nuid, s->gpa);
  132. char *str = studentToString(s);
  133. printf("%s\n", str);
  134. free(str);
  135. return;
  136. }
  137.  
  138. void printRoster(Student *s, int n) {
  139.  
  140. int i;
  141. for(i=0; i<n; i++) {
  142. printStudent(&s[i]);
  143. }
  144. return;
  145. }
  146.  
  147. /**
  148. * This function takes a student structure
  149. * and returns a string representation of it
  150. */
  151. char * studentToString(const Student *s) {
  152. //you could add up all characters: int length = strlen(s->firstName) + strlen(s->lastName) + ...
  153. char temp[1000];
  154. sprintf(temp, "%s, %s (%d) GPA = %.2f", s->lastName, s->firstName, s->nuid, s->gpa);
  155. char * result = (char *) malloc( (strlen(temp) + 1) * sizeof(char));
  156. strcpy(result, temp);
  157. return result;
  158. }
  159.  
  160. ```
  161.  
  162. ## Objects in Java
  163.  
  164. * Java is an object-oriented programming language and supports "objects" through the use of classes (it is a class-based OOP language)
  165. * An *object* is an entity with identity, state, and behavior
  166. * Identity: a class provides a blue-print for how to create *instances* of an object, each *instance* has identity (it is distinct from other instances)
  167. * State simply means that a class has *member variables*
  168. * Behavior: an object may also have *member methods*
  169. * Example: let's create a student object
  170.  
  171. ### Visibility
  172.  
  173. * member variables (and methods) can be made:
  174. * `private` only instances of a class can "see" the variables
  175. * `protected` only instances and subclasses can see the variables (involves inheritance)
  176. * `public` any piece of code can see the variables
  177. * In general, if a piece of code can see a variable, it can change it, this is bad: akin to create global variables
  178. * It is best practice to make all variables `private` unless there is a very good reason to do so.
  179. * You still want to interact with the object, so you can define getters and setters (accessor/mutator methods)
  180. * Advantages:
  181. * Lack of setters means you can design immutable objects (immutability is a very good thing in multithreaded programming)
  182. * getters/setters allow for data validation
  183. * Disadvantages: lotsotyping, solved with an IDE
  184. * If we make things immutable, how do we set values initially?
  185.  
  186. ### Constructor methods
  187.  
  188. * Constructor methods have the same name as the class, no return type, but may take any number of arguments
  189. * Multiple constructors can be defined
  190. * Constructor methods can be invoked (called) using the `new` keyword
  191. * If you do not define a constructor, a default, no-argument one will be provided for you, it simply sets all values to default values (0, 0.0, `null`, etc.)
  192. * The `this` keyword is used to refer to an object's own variables and methods (referred to as "open recursion")
  193. * If you define a constructor, the default no-argument constructor goes away
  194.  
  195. ## Misc
  196.  
  197. * The `toString()` method can be overridden/defined for conveniently printing an object in a human-readable format
  198. * Recall the `static` keyword: it makes a variable or method part of the class rather than instances of the class, it is best to use the `final` keyword to make it a constant (so nothing can change it)
  199.  
  200. * One object may contain other objects, this is known as *composition*
  201.  
  202. * Recall what *abstraction* is:
  203. * Procedural Abstraction: what does the `sqrt()` function do? How does it do it?
  204. * Object abstraction: the representation of an object is internal to the object and irrelevant to the outside world.
  205. * The outside world merely interacts with an object by calling its `public` methods
  206.  
  207. * Copy constructors: you can define a constructor that takes an object and constructs a new copy of it.
  208.  
  209.  
  210.  
  211.  
  212.  
  213. ```text
  214.  
  215.  
  216.  
  217.  
  218.  
  219.  
  220.  
  221.  
  222.  
  223.  
  224.  
  225.  
  226.  
  227.  
  228.  
  229.  
  230.  
  231. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement