Create intances in C - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Create intances in C

nhchengnhcheng Posts: 2Member
I need a way to create 2 instances in C.
Here's the flow:-

orig_task_A sends messages to display_task() via interface_A();
orig_tast_B sends messages to display_task() via interface_B().

From the source of input (either interface_A() or interface_B()), display_task() knows whether the messages come from task_A and task_B.

My question is how can we create interface_A() and interface_B() which basically does the same thing, but serving different orig_task.

I know by creating an abstract class in C++, I can create as many instances I can. But I need to have a methology in C that does the same thing as C++ does.

Any idea anyone?


  • vijayshankarbvijayshankarb Posts: 2Member
    Blw is a short program I wrote, uses void *pointers & function pointers to achieve the purpose. The struct task is the interface but its funtask can be set to different functions to achieve polymorphism in C.

    typedef struct task Task;
    typedef struct A A;
    typedef struct B B;

    struct A
    int a_value;

    struct B
    int b_value;

    struct task
    void *t;
    void (*funcTask)(Task*);
    A* getA()
    A* ptr = malloc(sizeof(A));
    ptr->a_value = 911;
    B* getB()
    B* ptr = malloc(sizeof(B));
    ptr->b_value = 729;

    void display_A_task(Task *task)
    A * aa= (A*)task->t;
    printf("%d", aa->a_value);

    void display_B_task(Task *task)
    B *bb = (B*)task->t;
    printf("%d", bb->b_value);
    Task* getTaskFromA(A *a_task)
    Task *TaskA;
    TaskA = (Task*)malloc(sizeof(Task));
    TaskA->t = a_task;
    TaskA->funcTask = display_A_task;
    return TaskA;

    Task* getTaskFromB(B *b_task)
    Task *TaskB;
    TaskB = (Task*)malloc(sizeof(Task));
    TaskB->t = b_task;
    TaskB->funcTask = display_B_task;
    return TaskB;

    void display_task()
    Task *ta;
    Task *tb;
    ta = getTaskFromA(getA());
    tb = getTaskFromB(getB());

    int main(void)

Sign In or Register to comment.