Constructor Pattern
Part of the Object Oriented Programming section of Coddy's C journey — lesson 12 of 61.
In languages like Java or C++, you create objects using constructors—special functions that automatically allocate memory and initialize fields. C has no such feature, but we can simulate it with a simple pattern: a create_ function.
A constructor function in C typically does three things: allocates memory with malloc, initializes all fields to proper values, and returns a pointer to the new object:
typedef struct {
char *name;
int age;
} Person;
Person *create_person(const char *name, int age) {
Person *p = malloc(sizeof(Person));
p->name = malloc(strlen(name) + 1);
strcpy(p->name, name);
p->age = age;
return p;
}
The function returns a pointer because the object lives on the heap, not the stack. This means it persists after the function returns and can be passed around freely. The caller uses it like this:
Person *alice = create_person("Alice", 30);
printf("%s is %d years old\n", alice->name, alice->age);
Notice how the constructor handles all the messy details—allocating the struct, allocating space for the string, and copying the data. The caller just provides the initial values and receives a ready-to-use object. This encapsulates the creation logic in one place, making your code cleaner and less error-prone.
Challenge
EasyLet's build a Book module that uses the constructor pattern to create book objects on the heap. You'll practice writing a create_ function that handles all the memory allocation and initialization, returning a ready-to-use pointer.
You'll create three files:
book.h: Declare aBookstruct with two members:char *title(a pointer to a dynamically allocated string) andint pages. Also declare a constructor functioncreate_bookthat takes a title string and page count, then returns a pointer to a newly created Book. Use include guards with the symbolBOOK_H.book.c: Implement thecreate_bookfunction. Your constructor should allocate memory for the Book struct itself, then allocate separate memory for the title string (remember to account for the null terminator), copy the title into the new memory, set the pages field, and return the pointer to the new Book.main.c: Use your constructor to create a book and display its information.
You will receive two inputs: the book title (a string) and the number of pages (an integer).
In your main file, use create_book to create a new book with the provided values, then print its information in this format:
Title: {title}
Pages: {pages}For example, with inputs The C Programming Language and 272, the output would be:
Title: The C Programming Language
Pages: 272Remember that your constructor encapsulates all the creation logic—the caller simply provides the initial values and receives a fully initialized object ready to use.
Cheat sheet
A constructor function in C simulates object creation by allocating memory and initializing fields. It typically follows the create_ naming pattern.
A constructor function does three things:
- Allocates memory with
malloc - Initializes all fields to proper values
- Returns a pointer to the new object
Example constructor pattern:
typedef struct {
char *name;
int age;
} Person;
Person *create_person(const char *name, int age) {
Person *p = malloc(sizeof(Person));
p->name = malloc(strlen(name) + 1);
strcpy(p->name, name);
p->age = age;
return p;
}
Using the constructor:
Person *alice = create_person("Alice", 30);
printf("%s is %d years old\n", alice->name, alice->age);
The function returns a pointer because the object lives on the heap and persists after the function returns. This encapsulates creation logic in one place, making code cleaner and less error-prone.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include "book.h"
int main() {
char title[256];
int pages;
// Read input
fgets(title, sizeof(title), stdin);
// Remove newline if present
for (int i = 0; title[i]; i++) {
if (title[i] == '\n') {
title[i] = '\0';
break;
}
}
scanf("%d", &pages);
// TODO: Use create_book to create a new book with the provided values
// TODO: Print the book information in the required format:
// Title: {title}
// Pages: {pages}
// TODO: Don't forget to free allocated memory when done
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy