Anderson Green
Anderson Green

Reputation: 31840

Equivalent of Java's Object type in C

Does the C programming language have anything similar to Java's Object class? I realize that it would be difficult to implement something like this in a low-level language such as C, but I think it might be very useful nonetheless. If there is nothing like the Object type in C, then is there any way to mimic Java's Object type in C?

The main use case that I have in mind is the creation of arrays with multiple primitive types in C, to mimic an Object array in Java: Object[] hasMultipleTypes = [3, "Hi!", 5.00];

Upvotes: 1

Views: 605

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

Basic objects are not very complicated - set of data fields (struct) plus pointer to virtual methods table (VMT). Each member function takes pointer to "this" as first argument.

It is relatively straight forward to implement in C. I'd look for descriptions of original cross-compilers for C++ which were doing exactly this - convert object oriented code into plain C.

Approximate class:

struct MyClassVMT
 { 
    int *(method1)();
 }

struct MyClass 
{ 
  MyClassVMT* vmt;
  int field1;
}

void MyClass_Constructor(MyClass* pThis) { pThis.vmt = &_myClassVmt;}
void MyClass_nonVirtual (MyClass* pThis) {}
void MyClass_method1(MyClass* pThis) {}

MyClassVMT _myClassVmt;
_myClassVmt.mehtod1 = MyClass_method1;

// Usage
MyClass item;
MyClass_Constructor(&item);

MyClass_nonVirtual(&item); // non virtual method call
item.method1(&item); // virtual method call

Upvotes: 2

Related Questions