0

Kind of confused as to how I should implement a simple entity hierarchy in OOP style C. For example, here's the equivalent C++ code:

class Entity {
protected:
    float x, y;

    Entity(float x, float y) : x(x), y(y) { }

    virtual void update() = 0;
    virtual void render() = 0;
    virtual ~Entity() { }
};

class Player : public Entity {
    Player(float x, float y) : Entity(x, y) { } 

    void update() {

    }

    void render() {

    }
};

So right now I have a structure Entity that has two function pointers that will point to the update and render functions. Then I would have a Player structure which would have a pointer to the Entity structure so it can access the members. One thing I'm kind of confused about is how allocation would work... would I have a new_entity function perhaps that allocates an Entity structure? Could I have a new_player function that allocates an Entity ptr, and returns the Player structure, and will set the functions to point to the player_update, play_render functions, etc?

meh
  • 1
  • C does not have built-in support for object-oriented programming or inheritance. You can try to follow similar design patterns anyway, and it is sometimes a good idea to do so, but you're not going to see answers like "here's how to make one struct inherit from another" or "here's how to define a method". – user2357112 Jul 27 '16 at 21:20
  • 3
    You will end up writing a C++ clone, but not as good. Use the right language for the job. – Weather Vane Jul 27 '16 at 21:21
  • Do some research on the gcc extension `-fplan9-extensions` plus anonymous `struct` members. They are very interesting if you are not stuck with standard C. – too honest for this site Jul 27 '16 at 21:37
  • For an excellent article/tutorial on incomplete datatypes, encapsulation, data-hiding, dynamic linkage/late binding, opaque pointers and object oriented approaches to dynamic data-structures, see [**Object Oriented Programming in ANSI-C**](http://www.cs.rit.edu/~ats/books/ooc.pdf). – David C. Rankin Jul 28 '16 at 00:07
  • @WeatherVane I understand that, I'm not really writing an entire OOP program in C. I think I wrote my question wrong, I was more interested in dynamically dispatching methods but I think I've figured it out now. – meh Jul 28 '16 at 16:21

0 Answers0