Is it possible to program object oriented in C?

Asked

Viewed 9,703 times

19

There is the possibility to build a C program using POO?

I have looked on several websites for examples of this, but I have found nothing concrete, which tells me whether or not it really gives. If yes, please put at least one example of code.

  • I suggest to try to better understand what POO is. The answers of mgibsonbr and Luiz Vieira in this question were the only ones I’ve seen so far here at Sopt that offer a useful and very good definition of POO. Object-oriented programming is not about coding genius technological tricks to achieve inheritance and polymorphism in a language that does not offer this as a natural resource. Object-oriented programming is about using your concepts in a language that abstracts the techniques that the compiler uses to make the concepts work.

  • I don’t want to do POO in C, because I know there is no way, I want to "emulate", to be able to use some resources.

2 answers

28


I will say something concrete: it gives! But it does not usually compensate in most cases. What I would say the same for all OOP.

Perhaps the best example of a C program using OOP is GTK which uses the entire system of Gobject (reference).

There’s even a book on the subject.

Initially C++ only generated a code in C. The code was somewhat confusing, but it was a program made with OOP techniques (originally written in C++) and instead of generating binary code, it generated a source in C.

Whichever programming language can perform anything. The difference is the level of abstraction it gives to build codes within certain patterns. In a way OOP is a design pattern, it’s just a form of abstraction. Design patterns are everywhere. Everything can be applied in any language, the difference is that some facilitate the work.

Assembly can be programmed as OOP.

In C you would have to write code to handle everything other languages do in their basic structure. It gets big, messy and ugly, most errors will probably only be noticed at runtime, outside be slower to develop, will have a lot of manual work, has chance to cause more problems. But it meets every need.

You can produce the encapsulation, inheritance and polymorphism that are the three basic techniques of OOP. It can also have abstraction and overload, as some definitions of what is OOP understand. Again, it doesn’t look good, some techniques may not make up for the effort. There may be more performance loss than in a syntax and semantics language for OOP.

None of this means that C is an OOP language, only that it is possible to use the same pattern if you want too.

I’ve answered most of that one another question.

As the focus is not on the details of how to do this I will leave the links below as additional information:

  • I wanted to find a way to just "separate" things, not have to put everything in one file.

  • I’m not sure I understand what you call separating things. Object orientation has a lot to do with putting things together. But you may be talking about something else, decoupling. There are techniques that don’t need to be OOP to better organize the code.

  • I didn’t know that side of C, but is it advantageous to program like this? I refer to the book link.

  • 1

    A link that may complement http://answall.com/a/53151/3635

  • My initial goal was to get things "uncoupled" by separating into different files, but as you commented on encapsulation, inheritance and polymorphism using C, this would be a great help bonus for me.

  • 1

    @Meuchapeu in general does not. But the construction of a GUI is so complex, it is enough to compensate. To tell the truth GUI is one of the few things where OOP really fits perfectly. The rest is bar forcing :) Of course, everything has time to do. But if you really need to do OOP, it’s better to use another language. Only if C is explicit requirement should this solution be adopted. This was the case for Gnome/GTK.

  • 1

    @Guilhermenascimento found what I was looking for.

  • @Jonathanbarcela after I try complementary but uncoupling does not need OOP. I don’t know if this fits more in this question that is clearly about OOP and not decoupling in imperative language.

  • @bigown We will leave the focus on POO even when to the decoupling I create another question if necessary. Thank you.

  • Monsters like Gobject came about because the free C++ compiler (gcc) was considered very bad, and there was/was a certain bias of the free software community with C++. The problems of gcc have been solved for a long time, so it’s much easier to use C++ and avoid the more esoteric resources of it to not curl up.

  • @epx, yes, that’s right. There’s also some difficulty interoperability with C++.

Show 6 more comments

3

The closest to OO that the C language can reach is using TAD’s (Abstract Types of Data). And yes, you can "separate" the interface of an ADT implementation into separate files (in fact, ideally you separate them).

Conceptually, a TAD is a set of structured data and the operations that can be performed on that data.

Usually, a TAD is implemented in the form of two modules (separate files): the implementation and the interface.

The advantages of using an ADT are: encapsulation (a feature of OO), safety, flexibility and reuse (another feature of OO).

I will give an example for vc in a simple TAD (from a point in a two-dimensional space). You will create 3 files in a project (can be Codeblocks or DEV):

  1. point. c
  2. point. h and
  3. testa_point. h

Follow the implementations of all of them in order (the project works perfectly): FILE point. c:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "ponto.h"

struct ponto {
    float x;
    float y;
};

Ponto *pto_cria (float x, float y){
    Ponto *p = (Ponto*) malloc(sizeof(Ponto));
    if (p == NULL) {
        printf("Memoria insuficiente!\n");
        exit(1);
    }
    p->x = x;
    p->y = y;
    return p;
}

void pto_libera (Ponto *p){
    free(p);
}

void pto_acessa (Ponto *p, float *x, float *y){
    *x = p->x;
    *y = p->y;
}

void pto_atribui (Ponto *p, float x, float y){
    p->x = x;
    p->y = y;
}

float pto_distancia (Ponto *p1, Ponto *p2){
    float dx = p2->x - p1->x;
    float dy = p2->y - p1->y;
    return sqrt(dx*dx + dy*dy);
}

FILE point. h

/* TAD: Ponto (x,y) */
/* Tipo exportado */
typedef struct ponto Ponto;

/* Funçőes exportadas */
/* Funçăo cria - Aloca e retorna um ponto com coordenadas (x,y) */
Ponto *pto_cria (float x, float y);

/* Funçăo libera - Libera a memória de um ponto previamente criado */
void pto_libera (Ponto * p);

/* Funçăo acessa - Retorna os valores das coordenadas de um ponto */
void pto_acessa (Ponto *p, float *x, float *y);

/* Funçăo atribui - Atribui novos valores ŕs coordenadas de um ponto */
void pto_atribui (Ponto *p, float x, float y);

/* Funçăo distancia - Retorna a distância entre dois pontos */
float pto_distancia (Ponto *p1, Ponto *p2);

FILE testa_point. c:

/* Funçăo : Exemplo de uso do TAD Ponto
/ Autor : Edkallenn
/ Data : 06/04/2012
/ Observaçőes: Salve este arquivo como testa_ponto.c
*/
#include <stdio.h>
#include <math.h>
#include "ponto.h"

int main (void)
{
    //float x, y;

    Ponto *p = pto_cria(2.0,1.0);
    Ponto *q = pto_cria(3.4,2.1);

    float d = pto_distancia(p,q);

    printf("Distancia entre pontos: %f\n",d);

    pto_libera(q);
    pto_libera(p);

    return 0;
}

NOTE that we have the type definition (with the fields, "properties" or "attributes" of the type), we have the type functions (or the "methods" that the type, or object, as you want, can perform) and we have the file (which would be the main) that tests the type.

DETAIL: this is not OO. In practice, MANY of the Object Orientation features are out. This is very close to what would be a "dirty" oo in a procedural language.

Understands?

Links for you to better understand... About TAD: - https://www.inf.ufes.br/~pdcosta/teaching/2011-2-data structures/slides/Class8%28TADs%29.pdf - http://wiki.icmc.usp.br/images/f/fd/AulaTAD.pdf - https://webserver2.tecgraf.puc-rio.br/~Marcio/cursos/dloads/prog3_C++/material/TAD.pdf - https://blogdecodigo.wordpress.com/2012/08/02/tad-tipo-abstratos-de-dados/ (java)

And the project files: https://github.com/ed1rac/AulasEstruturasDados/tree/master/2016/TAD_ponto

Anything, in the comments.

As the colleague spoke up there, it’s a lot of work! If you want to use Part OO for a genuinely OO language like C++, Java or C#

Browser other questions tagged

You are not signed in. Login or sign up in order to post.