Concept
How can factory functions simplify the creation of structure instances?
ComputerScienceOne / Factory Functions
"Properly creating and initializing structure instances can be a complex and tedious task. However, it is likely that we will need to repeat this operation over and over. We can simplify our task if we write a utility function that creates a structure instance for us. We provide the function the values we want initialized to. Such functions are sometimes referred to as factory functions as they can be used to manufacture as many instances as we want (in object-oriented programming languages, such methods are called constructors). We will need to take care that we make deep copies of any dynamically allocated elements such as strings. Shallow copies where references are shared may lead to unexpected behavior as changes to one string may affect multiple structures.\n\n/**\n\n* This function creates a new student structure with the\n\n* given values.\n\n*/\n\nStudent * createStudent(const char *firstName,\n\nconst char *lastName,\n\nint id,\n\ndouble gpa) {\n\nStudent *s = NULL;\n\ns = (Student *) malloc(sizeof(Student) * 1);\n\n//make a deep copy of the strings\n\ns->firstName = (char *)malloc(sizeof(char)*(strlen(firstName)+1));\n\nstrcpy(s->firstName, firstName);\n\ns->lastName = (char *)malloc(sizeof(char)*(strlen(lastName)+1));\n\nstrcpy(s->lastName, lastName);\n\ns->id = id;\n\ns->gpa = gpa;\n\nreturn s;\n\n}"
Related Ideas
- How can you create a deep copy of a Student structure?ComputerScienceOne · To String Functions
- How do you dynamically allocate and initialize a structure?ComputerScienceOne · Selection Operators
- How are structure instances declared and initialized?ComputerScienceOne · Declaration & Initialization
- How can structures be dynamically allocated?ComputerScienceOne · Declaration & Initialization
- How should a class manage owned collections and avoid shallow copies?ComputerScienceOne · Composition
- Why are functions useful in programming?ComputerScienceOne · Functions
- How can constructors call one another and copy objects?ComputerScienceOne · Constructors
- How do you access members through a pointer to a structure?ComputerScienceOne · Selection Operators