This article is an automatic translation.
Objects in C - Christopher Villamarín Projects
Based on the book Object-oriented Programming with Ansi-C by Axel-Tobias Schreiner.
Encapsulation
A base struct called Class is defined. From this,
more objects can be created that inherit the same attributes and methods.
The design allows for efficient reuse and management of attributes.
typedef struct {size_t size;void * (* ctor) (void * self, va_list * app);void * (* dtor) (void * self);void * (* clone) (const void * self);size_t (* sizeOf) (const void * self);int (* differ) (const void * self, const void * other);char * (* toString) (const void * self);} Class;/* Overloaded methods: */void * new(const void * _class, ...);void delete(void * self);void * clone(const void * self);int differ(const void * self, const void * other);size_t sizeOf(const void * self);char * toString(const void * self);
Using the repository
Object management simplifies memory management in C. Consider the
example of initializing a string using the String class:
#include "String.h"#include <stdlib.h>int main() {void * text = new(String, "Hello world");printf("%s", toString(text));return 0;}
This approach hides memory management in the background, making the code cleaner and more readable.
Main functions
- Constructor: Initializes any object in a standardized way
with
new(). For example:void * text = new(String, "Hello, world"); - Cloner: Creates an independent copy of the object:
void * textCopy = clone(text);
- Destructor: Frees the object's memory using:
delete(text);
- toString: Returns the object's content as a printable string:
printf("text = %s\n", toString(text));
Usage examples
To compile the examples and see the results in the console, use the commands:
make examples && make run_examples
The example code is in the examples folder.
Tests
To verify the integrity of the implemented functions, you can run the tests with:
make tests
The tests use the acutest.h library. This allows adding more functionalities and testing them.
Cleanup
To remove all compiled files, use the command:
make clean