OOP in C ... kinda
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 :)
Written by Mariz Melo
Related protips
4 Responses
Still can't get methods :(
OOP depends on methods.
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 .
Thank you guys. @fuadsaud I've modified to simulate "methods" now.
@jmarizgit still no 'this' reference :(