0

While looking at someone's code i was struck by a way of representing data which, in a C context, seemed strange to me :

This person needed to represent different kind of geometries for a raytracer, each geometries while being different had similarities in their structures. So this person decided to represent the geometries through more or less abstract structs linked together through pointers.

s_entities -> s_scene_object -> s_sphere
s_entities -> s_scene_object -> s_plane
s_entities -> s_pointlight

i was wondering why one would decompose its data in C through abstraction layers instead of having an all-encompassing struct for each kind of data.

One explanation would be to reduce overhead if you have functions that operate on a certain layer of abstration of your data. right ?

it seems to me like remnants of OOP habits.

  • Unless you show us the structs, your question cannot really be answered. As Fred Brooks wrote: "Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won’t usually need your flowcharts; they’ll be obvious." – Tomek Szpakowicz Jan 31 '14 at 09:38
  • just added link to source code. i wanted to link to each specific struct definition but stack overflow doesnt allow me to (regarding my reputation level) –  Jan 31 '14 at 09:48

1 Answers1

2

You say "remnants of OOP habits" as if that's something that's obviously not OK in C. I'd say you're wrong, there are rather large collections of very heavily object-oriented code in C. It works.

Object-orientedness is a way to arrange and model things, it's not tied to programming languages. C is low-level enough that you can do all sorts of programming paradigms in it; you'll often have to implement much of the paradigm yourself since there is little support from the language, but OO is pretty straight-forward.

It's not very clear from your example, but a more typical way to model things like that in C is by embeddeding the more basic data structure (superclass) inside the more specialized, utilizing the fact that the first member in a C struct is at offset 0 from the struct itself:

typedef struct {
  float x, y, z;
} Shape;

typedef struct {
  Shape shape;
  float radius;
} Sphere;
unwind
  • 391,730
  • 64
  • 469
  • 606
  • doesn't it make the data component "harder" to access ? Also harder to initialize ? –  Jan 31 '14 at 09:31
  • +1 for OOP habits not being a bad thing on C. It's perfectly valid, and it surely helps to manage complexity in big projects. – Filipe Gonçalves Jan 31 '14 at 09:59