Is it possible to program object-oriented in C?

16

Is it possible to build a C program using OOP?

I looked at several sites for examples of this, but I did not find anything concrete, that really tells me whether or not it works. If so, please put at least one code sample.

    
asked by anonymous 11.08.2015 / 21:45

2 answers

25

I'll say something concrete. 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 program made in C that uses OOP is the GTK that uses every < a href="https://en.wikipedia.org/wiki/GObject"> GObject ( Reference ).

You even have 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 a binary code, it generated a source in C.

Any programming language can do anything. The difference is the level of abstraction it gives to construct codes within certain patterns. OOP is a design standard. Design patterns are everywhere . Everything can be applied in any language, the difference is that some make it easier.

Assembly can be programmed as OOP.

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

You can produce the encapsulation, inheritance, and polymorphism that are the three basic techniques of OOP. It may also have abstraction and overhead, as some definitions of what OOP mean. Again, it does not look good, some techniques might not make up for it. There may be more loss of performance than in a language with syntax and semantics proper to OOP.

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

I've answered most of this in another question .

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

11.08.2015 / 21:50
1

The closest to OO that Language C can get is using TAD's (Abstract Data Types). And yes, you can "separate" the interface from implementing a TAD into separate files (in fact, ideally you should separate them).

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

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

The advantages of using a TAD are: encapsulation (a feature of OO), security, flexibility and reuse (another feature of OO).

I'll give you an example for a simple TAD (from one point in a two-dimensional space). You will create 3 files in a project (it can be from CodeBlocks or DEV):

  • dot.c
  • dot. h and
  • testa_ponto.h
  • Following the implementations of all of them, in order (the project works perfectly): ARCHIVE dot.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);
    }
    

    ARCHIVE dot.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);
    

    testa_ponto.c FILE:

    /* 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;
    }
    

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

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

    Understand?

    Links to understand better ... About TAD:  - link  - link  - link  - link (in java)

    And the project files: link

    Anything in the comments.

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

        
    08.06.2017 / 02:29