Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In C anyway you an do it the way cfront used to do it in the early days of C++ when the C++ code was translated into C. But you need to be quite disciplined and do all the grunt work manually.</p> <p>Your 'classes' have to be initialized using a function that performs the constructor's work. this will include initializing a pointer to a table of polymorphic function pointers for the virtual functions. Virtual function calls have to be made through the vtbl function pointer (which will point to a structure of function pointers - one for each virtual function).</p> <p>The virtual function structure for each derived calss needs to be a super-set of the one for the base class.</p> <p>Some of the mechanics of this might be hidden/aided using macros.</p> <p>Miro Samek's first edition of <a href="http://www.state-machine.com/resources/index.htm" rel="nofollow noreferrer">"Practical Statecharts in C/C++"</a> has an Appendix A - "C+ - Object Oriented Programming in C" that has such macros. It looks like this was dropped from the second edition. Probably because it's more trouble than it's worth. Just use C++ if you want to do this...</p> <p>You should also read <a href="http://www.pearsonhighered.com/educator/product/Inside-the-C-Object-Model/9780201834543.page" rel="nofollow noreferrer">Lippman's "Inside the C++ Object Model"</a> which goes into gory details about how C++ works behind the scenes, often with snippets of how things might work in C.</p> <hr> <p>I think I see what you're after. Maybe.</p> <p>How can something like this work:</p> <pre><code>typedef struct foo { int a; } foo; void doSomething( foo f); // note: f is passed by value typedef struct bar { foo base; int b; } bar; int main() { bar b = { { 1 }, 2}; doSomething( b); // how can the compiler know to 'slice' b // down to a foo? return 0; } </code></pre> <p>Well you can't do that as simply as that without language support - you'd need to do some things manually (that's what it means to not have language support):</p> <pre><code> doSomething( b.base); // this works </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload