Is C an Object Oriented Language?

C is a good and complex language, and enables you the well the memory managment, however, the original question is: can we transform C language into Object Oriented Language without modify the compiler? And the answer is: YES, we can.

We wont have all the C++ power doing this, cannot specify private/public/protected methods, hierarchy and other stuff available on C++, only will have the power to create some interface classes and fillit with functions in runtime.

    Well, in my research for exploring the C programming world capabilities, and push it to the limit, i wrote a code for transform C into a pseudo-object-oriented language

    The proposed method is to create a class who in OOP is called Interface.

typedef struct myclass
{
    int value;
    void (*method)(void *);
} my_class;

    Inmmidiatly, this “method” must be created, because is not well defined, be as we can see, in the program compiler, this method can work only for this class and only will be assigned to the “class” instances.

    Look a common function that can fill with this pseudo-class “my_class“.

void some_function(void * local_ref)
{
printf(“Your number is: %d”, ((my_class *)local_ref)->value );
}

    Then, we have a pseudo-class interface and a associated method. Now, will see how to use it.

int _tmain(int argc, _TCHAR* argv[])
{
    //Is C an object oriented programming language?
    charstop[80];
    //Instance
my_class objectx;
objectx.value=21;
objectx.method=&some_function;    //Method call
objectx.method(&objectx);

    //Stop!
fgets(stop,80,stdin);

    return 0;
}

    Its clearly showed, an initialization of a pseudo-class called objectx. First of all, we assign to value (objectx.value) the value 21, and the method is defined by a function pointer, some_function. This is how we make an instance of the “class”, and create an object with methods and values-variables, and also can take references and other similar pseudo-classes assigned.

    To call this function, we also include the reference to the own class as a function parameter, because dont exist context switching for “this”, Maybe we can optimize and hide some of nasty code using C macros.

Related Posts

Leave a Reply