Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to use function pointers inside a struct like OOP in C

2 Answers

0 votes
// Struct With Multiple Function Pointers (“Methods”) (Object‑like Design)
 
#include <stdio.h>
 
typedef struct {
    void (*start)();
    void (*stop)();
} Motor;
 
void motorStart() { printf("Motor started\n"); }
void motorStop()  { printf("Motor stopped\n"); }
 
int main() {
    Motor m = { motorStart, motorStop };
 
    m.start();
    m.stop();
     
    return 0;
}
 
 
 
/*
run:
 
Motor started
Motor stopped
 
*/

 



answered May 12 by avibootz
0 votes
// Struct With Multiple Function Pointers
// “Methods” That Take the Struct Itself (OOP in C)

#include <stdio.h>

typedef struct Object {
    int x;

    void (*set)(struct Object*, int);
    void (*print)(struct Object*);
} Object;

void setX(Object* self, int v) {
    self->x = v;
}

void printX(Object* self) {
    printf("x = %d\n", self->x);
}

int main() {
    Object obj = { 10, setX, printX };
    
    obj.print(&obj);
    
    obj.set(&obj, 99);
    obj.print(&obj);

    return 0;
}


/*
run:

x = 10
x = 99

*/

 



answered May 12 by avibootz
edited May 12 by avibootz
...