C legacy coding style?

From: Alexei Zakharov (res0m4rf___at___verizon.net)
Date: 01/31/04


Date: Sat, 31 Jan 2004 00:26:40 GMT

I had a pleasure of dealing with some code recently that looked like this:

<code>
struct Node
{
// almost POD, but having non-virtual methods
    void foo();
};

struct MyNode
{
// almost POD also

    Node node_; // first field
    // more data fields...

    void bar();
};

// this is how the above structs are used
void StoreNode( Node * );
Node * RetrieveNode();

int main()
{
// store
    MyNode * n = new MyNode();
    StoreNode( & n->node_ );

// retrieve later
    Node * nn = RetrieveNode();
    MyNode * mn = ( MyNode * ) nn;
    mn->bar(); // actually works with my C++ compiler
}
</code>

I'm well aware that doing so in C++ is extremely fragile and not even
garanteed to work with another C++ compiler.

But this strikes me as a C-style technique which is equivalent to
inheritance in C++. Although in my C days I've never seen it in use. So my
question is if this is (was) widely used in C and if it's valid technique
complying with C standard. (of course methods should be removed from the
structs to compile this code with a C compiler).



Relevant Pages