-ms5fa
Last Updated: February 25, 2016
·
1.311K
· jmarizgit

OOP in C ... kinda

gcc
c

UPDATE: accepting "methods" now.

The C language don't provide us the concept of classes nor inheritance. Fortunately we can simulate that using structures.

link to test online:
https://compilr.com/jmarizsf/structures/structures.c

source code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//methods
int display(int age)
{ return age; }

//create Person struct
struct Person{
char *name;
int age;
int (*display)(int);
}person = {"Mariz Melo", 31, &display}; //simulating construct

//create Worker struct
struct Worker{
char *job;
struct Person person; //simulating inheritance
}worker = {"programer"};

int main(void){
struct Person samira = person; //new instance
struct Worker mariz = worker; //new instance
              mariz.person = person; //simulating inheritance

samira.name = "Samira Salour";
samira.age = 25;

printf("%s %d\n", samira.name, samira.display(samira.age));
printf("%s - %s\n", mariz.person.name, mariz.job);
return 0;
}

Code compiled using gcc 4.2.1

I am expecting some discussion about this one... bring it on :)

4 Responses
Add your response

1633

Still can't get methods :(

OOP depends on methods.

over 1 year ago ·
1638

Kevlin Henney had a really good lecture about whether you can do OOP in Java, which also demonstrated programming OO in ANSI C.

I can't find the link at the moment, but here is stackoverflow answer with demonstration of OOP in C: http://stackoverflow.com/questions/2181079/object-oriented-programming-in-c

Still, it's possible (and often expected) to do OOP in C .

over 1 year ago ·
1649

Thank you guys. @fuadsaud I've modified to simulate "methods" now.

over 1 year ago ·
1650

@jmarizgit still no 'this' reference :(

over 1 year ago ·