Course contentsShow
← C
Lesson 675 of 1,2199. Structures and UnionsFree lesson

Implementing an interface with function pointers in structs

Implementing an interface with function pointers in structs

What you'll learn: How to use function pointers inside a struct to create flexible, "pluggable" behavior similar to interfaces in high-level languages.

The Concept: A Remote Control for Logic

In C, a struct usually holds data like integers or arrays. However, by storing a function pointer inside a struct, you allow the struct to carry its own behavior.

Think of this like a universal remote control. The remote has a "Power" button, but that button does something different depending on whether it’s linked to a TV, a Fan, or a Stereo. By defining a standard set of function pointers, you create an Interface: a contract that says "any struct of this type will have a function named operate, but how it operates is up to the specific instance."

Building the Interface

To implement this, we define a struct where the members are pointers to functions. We then "plug in" specific functions when we initialize the struct.

#include <stdio.h>

// 1. Define the "Interface"
typedef struct {
    void (*speak)(void); // A pointer to a function that returns void
} AnimalInterface;

// 2. Create specific behaviors
void dog_bark() {
    printf("Woof! Woof!\n");
}

void cat_meow() {
    printf("Meow...\n");
}

int main() {
    // 3. Plug behaviors into the struct instances
    AnimalInterface dog = { .speak = dog_bark };
    AnimalInterface cat = { .speak = cat_meow };

    // 4. Use the interface
    // The caller doesn't need to know the internal logic, just that speak() exists.
    dog.speak(); // Outputs: Woof! Woof!
    cat.speak(); // Outputs: Meow...

    return 0;
}

Why This Matters

This pattern is the backbone of professional C programming, including the Linux Kernel and device drivers. It allows for decoupling.

Imagine you are writing a logging library. You could create a Logger struct with a function pointer log_message. One user might plug in a function that writes to a file, while another plugs in a function that sends the text over Wi-Fi. Your main program doesn't have to change; it simply calls my_logger.log_message(), trusting that the correct behavior has been "plugged in."

Key takeaway

By storing function pointers in a struct, you can treat functions like data, allowing different instances of the same struct type to perform different actions.