Re: Adding the ability to add functions into structures?
- From: jacob navia <jacob@xxxxxxxxxxxxxxxx>
- Date: Mon, 02 Jan 2006 22:46:16 +0100
Keith Thompson a écrit :
One difficulty with this approach, as compared to the equivalent in a language like C++ that support OO directly, is that you have to manually build and initialize the function table yourself; the compiler won't do it for you. If you forget to do this, Bad Things Happen; for example:
struct ArrayList obj; int count = obj.lpVtbl->GetCount();
invokes undefined behavior. But that's not a fatal flaw; it's easy enough to declare an object that provides a default initial value:
const struct ArrayListInterface ArrayListInterfaceDefault = { ... };
struct ArrayList ArrayListDefault = { &ArrayListInterfaceDefault, 0, ... }
and then:
struct ArrayList obj = ArrayListDefault; int count = obj.lpVtbl->GetCount();
will consistently give you 0.
Normally you would call a constructor function that returns a pointer to an allocated structure.
The advantage of this is the flexibility it gives you. You can change the behavior of a function at run time, by assigning the function pointer to another function. That function can call the old function pointer and then do something special, or can reimplement the old function completely. And this is achieved without having to change a single line in user code.
The array list object is patterned like its name-sake in C#: a flexible array that can hold items and grows automatically if needed.
Another plus point is that the name-space of the interface is private to the containing structure, so you can use simple names like "Add" or "Delete" without fear that it will clash with the user name space.
jacob .
- References:
- Re: Adding the ability to add functions into structures?
- From: Emmanuel Delahaye
- Re: Adding the ability to add functions into structures?
- From: Jordan Abel
- Re: Adding the ability to add functions into structures?
- From: jacob navia
- Re: Adding the ability to add functions into structures?
- From: Keith Thompson
- Re: Adding the ability to add functions into structures?
- Prev by Date: Re: Getc or Getchar is not reading data
- Next by Date: Re: gets() - dangerous?
- Previous by thread: Re: Adding the ability to add functions into structures?
- Next by thread: Re: Adding the ability to add functions into structures?
- Index(es):
Relevant Pages
|