This C code demonstrates the concept of interfaces using function pointers. Here’s a breakdown of the changes and explanations:
We define a geometry struct that contains function pointers for area and perim. This acts as our interface.
We define rect and circle structs to represent rectangles and circles.
We implement the interface functions for both rect and circle. These functions take a void* parameter, which we cast to the appropriate struct type inside the function.
The measure function takes a void* for the shape and a geometry* for the interface. It calls the interface functions through the function pointers.
In main, we create instances of rect and circle, and corresponding geometry structs with the appropriate function pointers.
We call measure with each shape and its corresponding geometry interface.
To compile and run this program:
This example demonstrates how to simulate interfaces in C using function pointers. While C doesn’t have built-in support for interfaces like some higher-level languages, this pattern allows for a similar level of abstraction and polymorphism.