-6

Possible Duplicate:
Can you write object oriented code in C?

Can I use C(not C++!!!) for Object Oriented Programming?

Community
  • 1
  • 1
epaminonda nicu
  • 115
  • 2
  • 3
  • Yes you can. The X window system did it (using void * etc). – Ed Heal Feb 10 '12 at 08:37
  • You can, but you'd probably end up wasting 99% of your time writing a lot of stuff that already exists in other object oriented languages based on C, like C++ and Objective-C as two examples. – Jasarien Feb 10 '12 at 09:29

4 Answers4

2

Yes! Object Oriented Programming is A Good Thing, and is very, very possible in C.

Creating objects is not limited to C++ or any other language. Data hiding is easier with C++ and other fourth-generation languages, and having languages that automagically clean up after themselves makes programming easier. BUT! There's always an overhead cost for making the programmer's life easier.

Using pointers to structures is one easy way to implement OOP in C. Linked lists spring to mind immediately. For a (voice)mail system, you could have a mailbox struct that "contained" message structs (as well as the mailbox's own data, of course). Hiding the implementation of a message would be easy; all you'd have to know is that the message had pointers to its mailbox, the previous message, and the next message. Of course, you'd know that a certain set of functions would operate on a mailbox and another set that worked with a message.

The advantage C++ has over C when it comes to OOP is that C++ easily enables you to put methods (actually pointers to them!) into objects. In truth, the methods are just special cases of objects....

Ernest_CT
  • 62
  • 4
1

There is a book: "Object-Orientated Programming with ANSI-C".

Proteas
  • 89
  • 5
0

I was always under the impression that you couldn't. This is why: C++ was originally called "C with Objects." There might be a way to, in effect, fake OOP C, but I don't think that it's strictly 100% OOP.

greater minds will be able to clarify this, though

Jamie Taylor
  • 1,644
  • 1
  • 18
  • 42
0

It is a matter of discipline, and you have to build your own framework AND stick to it.

You will have a lot of "syntactical sugar" and you won't have the beauty of expression that a well designed OOP language has. But yes, you can.

Even polymorphism is possible, but you have to write and maintain the appropriate code by yourself.

STRING to_string(OBJECT o)
{
  switch get_class(o) {
    case CLASS_OBJECT:
      return "object";
      break;
    default:
      return "something";
      break;
  }
}

...

Martin B
  • 23,670
  • 6
  • 53
  • 72
Peter Miehle
  • 5,984
  • 2
  • 38
  • 55