using virtual function in c

Discussion in 'C Programming' started by mohan, Jan 9, 2006.

  1. mohan

    mohan Guest

    Hi All,

    How to implement virtual concept in c.

    TIA

    Mohan
    mohan, Jan 9, 2006
    #1
    1. Advertising

  2. "mohan" <> writes:
    > How to implement virtual concept in c.


    Probably by writing a C++ compiler in C.

    C doesn't have virtual functions. What problem are you trying to
    solve?

    --
    Keith Thompson (The_Other_Keith) <http://www.ghoti.net/~kst>
    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
    We must do something. This is something. Therefore, we must do this.
    Keith Thompson, Jan 9, 2006
    #2
    1. Advertising

  3. mohan

    Jordan Abel Guest

    On 2006-01-09, mohan <> wrote:
    > Hi All,
    >
    > How to implement virtual concept in c.
    >
    > TIA
    >
    > Mohan


    Assuming that by "virtual" you mean something along the lines of how
    that word is used in another language which resembles, but most
    emphatically is not the same as, C...

    Have, as the first member of some struct, a pointer to another struct
    consisting of members of pointer-to-function types.
    Jordan Abel, Jan 9, 2006
    #3
  4. mohan

    Default User Guest

    mohan wrote:

    > Hi All,
    >
    > How to implement virtual concept in c.


    Tell us what YOU think this means, and why you want to do it in C.



    Brian
    Default User, Jan 9, 2006
    #4
  5. mohan

    mohan Guest

    Well I wanted to achieve dynamic polymorphism in c . Ie calling function
    dynamically
    depending upon the type

    Mohan

    "Default User" <> wrote in message
    news:...
    > mohan wrote:
    >
    > > Hi All,
    > >
    > > How to implement virtual concept in c.

    >
    > Tell us what YOU think this means, and why you want to do it in C.
    >
    >
    >
    > Brian
    mohan, Jan 9, 2006
    #5
  6. mohan

    Chuck F. Guest

    *** top-posting corrected ***
    mohan wrote:
    > "Default User" <> wrote:
    >> mohan wrote:
    >>>
    >>> How to implement virtual concept in c.

    >>
    >> Tell us what YOU think this means, and why you want to do it
    >> in C.

    >
    > Well I wanted to achieve dynamic polymorphism in c . Ie calling
    > function dynamically depending upon the type


    Don't top-post. Your answer belongs after, or intermixed with, the
    snipped quoted material to which you reply.

    C doesn't allow this. Actually, neither does C++, it fakes it by
    modifying all function names. That is why linking from C++ to
    normal languages is virtually impossible, and why the 'extern "C"'
    directive is available in C++.

    --
    "If you want to post a followup via groups.google.com, don't use
    the broken "Reply" link at the bottom of the article. Click on
    "show options" at the top of the article, then click on the
    "Reply" at the bottom of the article headers." - Keith Thompson
    More details at: <http://cfaj.freeshell.org/google/>
    Chuck F., Jan 9, 2006
    #6
  7. Chuck F. wrote:
    > *** top-posting corrected ***
    > mohan wrote:
    >
    >> "Default User" <> wrote:
    >>
    >>> mohan wrote:
    >>>
    >>>>
    >>>> How to implement virtual concept in c.
    >>>
    >>>
    >>> Tell us what YOU think this means, and why you want to do it
    >>> in C.

    >>
    >>
    > > Well I wanted to achieve dynamic polymorphism in c . Ie calling
    > > function dynamically depending upon the type

    >
    > Don't top-post. Your answer belongs after, or intermixed with, the
    > snipped quoted material to which you reply.
    >
    > C doesn't allow this. Actually, neither does C++, it fakes it by
    > modifying all function names. That is why linking from C++ to normal
    > languages is virtually impossible, and why the 'extern "C"' directive is
    > available in C++.
    >


    The language syntax does not natively support polymorphisms, but you can
    "achieve dynamic polymorphisms" as a construct.

    I do data conversion services to fill my time between projects, typically
    using "alien" data that I decode into "data types" that are converted to the
    target system/application. I have a library of conversion routines that take
    the identified alien "data type" normalizes, typically array of char, so it
    can be converted to the target system/application data type storage.

    Here is a simple example of how you can achieve polymorphisms. How useful you
    will find it depends on what you are really want to achieve, syntactic
    polymorphisms, or emulated polymorphisms.


    #include <stdio.h>
    #include <stdlib.h>

    void longMyFunc(long ll)
    {
    printf("long parameter virtual function (%d)\n",ll);
    }

    void intMyFunc(int ii)
    {
    printf("int parameter virtual function (%d)\n",ii);
    }

    void doubleMyFunc(double dd)
    {
    printf("double parameter virtual function (%.2f)\n",dd);
    }

    void stringMyFunc(char *ss)
    {
    printf("string parameter virtual function (%s)\n",ss);
    }

    void unknown_virt_arg(int varg)
    {
    printf("unknown virtual parameter argument (%d)\n",varg);
    }

    enum {
    VLONG = 1,
    VINT,
    VDOUBLE,
    VSTRING
    };
    #define VIRTUAL_ARG(x) x

    void myFunc(int varg,void *arg)
    {
    union
    {
    void *vv;
    long *ll;
    int *ii;
    double *dd;
    char *ss;
    } virt_arg;

    virt_arg.vv = arg;
    switch(varg)
    {
    default : unknown_virt_arg(varg); break;
    case VLONG : longMyFunc(*virt_arg.ll); break;
    case VINT : intMyFunc(*virt_arg.ii); break;
    case VDOUBLE : doubleMyFunc(*virt_arg.dd); break;
    case VSTRING : stringMyFunc(virt_arg.ss); break;
    }
    }

    int main(int argc,char **argv)
    {
    long ll = 123;
    int ii = 456;
    double dd = (double)1234.56;
    char * ss = "123456";

    myFunc(VLONG,&ll);
    myFunc(VINT,&ii);
    myFunc(VDOUBLE,&dd);
    myFunc(VSTRING,ss);
    }
    Joseph Dionne, Jan 9, 2006
    #7
  8. mohan

    Default User Guest

    mohan wrote:

    > Well I wanted to achieve dynamic polymorphism in c .


    Why?

    > Ie calling function dynamically depending upon the type


    On the type of what? You haven't explained what it is that you want.
    Give examples. Explain why you don't want to use languages that already
    provide polymorphism.

    Your project specs are hazy at best.




    Brian
    Default User, Jan 9, 2006
    #8
  9. mohan

    Chris Torek Guest

    In article <SOtwf.4257$>
    Joseph Dionne <> wrote:
    >Here is a simple example of how you can achieve polymorphisms. ...


    This code will not work on the Data General Eclipse, because:

    [Snippage below no longer marked; I retained only the amount of
    code needed to show where it breaks. Note that this removed some
    error checking. I also re-ordered the code so that the problem
    will be more obvious.]

    >#include <stdio.h>
    >#include <stdlib.h>


    >void intMyFunc(int ii)
    >{
    > printf("int parameter virtual function (%d)\n",ii);
    >}
    >
    >enum {
    > VINT,
    > VSTRING
    >};
    >
    >int main(int argc,char **argv)
    >{
    > int ii = 456;
    >
    > myFunc(VINT,&ii);


    Here, the machine will convert &ii (a word pointer) to a byte pointer,
    by shifting it left one bit.

    >}
    >void myFunc(int varg,void *arg)
    >{
    > union
    > {
    > void *vv;
    > int *ii;
    > } virt_arg;
    >
    > virt_arg.vv = arg;


    Note that this will store a byte pointer in the union, even though
    the "int *ii" member will be assumed to hold a word pointer.

    > switch(varg)
    > {
    > case VINT : intMyFunc(*virt_arg.ii); break;


    Here, the machine will follow the word pointer -- but virt_arg.ii
    actually contains a byte pointer. The result is a runtime trap
    (mapped to a "segmentation fault" in DG/UX), as the value is not
    a legal word-address.

    We could make the call to intMyFunc work by doing this instead:

    case VINT : intMyFunc(*(int *)virt_arg.vv); break;

    but if we are going to do that, we might as well get rid of the
    union entirely, and just write:

    case VINT : intMyFunc(*(int *)arg); break;

    In either case, this will cause the compiler to insert the needed
    assembly-level instruction to shift the byte pointer right one bit,
    converting it back to a word pointer, before following the resulting
    pointer.

    > }
    >}


    In general, I prefer to simulate C++-like "virtual functions" using
    function pointers. There are at least two simple and sensible
    approaches (or three in more-limited situations), with somewhat
    different tradeoffs.

    Consider the following data structure, out of a "rogue"-like game:

    struct monster {
    char *name; /* e.g., "troll" or "umber hulk" */
    int level; /* dungeon level at which it normally appears */
    int armor_class; /* its native armor class */
    int initial_hitpoints; /* and number of hit points */
    ... and so on ...
    };

    Now, some monsters have "special" attacks, like a "floating eye"
    whose gaze can freeze the player (if he is not blind). These are
    often implemented by the kind of switch/case shown above, but it
    may be simpler in some situations to include this in the structure:

    struct monster {
    char *name; /* e.g., "troll" or "umber hulk" */
    int level; /* dungeon level at which it normally appears */
    void (*special_attack)(struct monster *, struct player *);
    ...

    Here we simply set the special_attack member of an instance of the
    data structure to point to the function that implements the special
    attack. (We can also set the pointer to NULL to indicate "no
    special attack", or just force the programmer to provide a no-op
    function for that case.)

    If there is only one "virtual function" for a given data structure,
    this method -- embedding the function pointer directly in the
    structure -- is almost always the way to go. In many programs,
    however, we find that some "polymorphic" data structure needs
    to be connected to many "virtual functions". In this case, it
    is often better, at least space-wise, to use a second level of
    indirection:

    struct monster_funcs {
    void (*special_attack)(struct monster *, struct player *);
    ... more function pointers ...
    };

    struct monster {
    char *name; /* e.g., "troll" or "umber hulk" */
    int level; /* dungeon level at which it normally appears */
    struct monster_funcs *ops; /* operations this kind of monster does */
    ...

    Now, instead of calling:

    (*monster->special_attack)(monster, player);

    at the appropriate point in the game, we might do this instead:

    (*monster->ops->special_attack)(monster, player);

    Although it conserves space, and makes it easier to set up the data
    structure in the first place, this method has two (relatively minor)
    drawbacks:

    - It takes an extra indirection to find the function to call
    (usually one more instruction per function-call). This is
    generally slightly slower than having the pointer directly
    in the data structure. If, after the program works, performance
    testing shows this to be a problem, you can always "hoist up"
    any key pointer(s), so it is not something you should worry
    about when first writing the code.

    - It makes it impossible to take an existing data structure and
    mutate "just one op". For instance, a floating eye might itself
    be blind-able, negating its special attack. Instead of having
    a flag ("this floating eye has been blinded, that one has not"),
    if we have the op pointer directly in the data structure --
    rather than in one data structure shared by all instances of
    that monster -- we can just zap out the op at that point:

    message("You blinded the eye!");
    m->special_attack = NULL; /* no more freezing gaze for THIS eye */

    Of course, you can handle this second problem the same way as you
    can handle the first: keep the "operations table", but hoist that
    particular op up into the data structure.
    --
    In-Real-Life: Chris Torek, Wind River Systems
    Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
    email: forget about it http://web.torek.net/torek/index.html
    Reading email is like searching for food in the garbage, thanks to spammers.
    Chris Torek, Jan 9, 2006
    #9
  10. Chris Torek wrote:
    > In article <SOtwf.4257$>
    > Joseph Dionne <> wrote:
    >
    >>Here is a simple example of how you can achieve polymorphisms. ...

    >
    >
    > This code will not work on the Data General Eclipse, because:
    >
    > [Snippage below no longer marked; I retained only the amount of
    > code needed to show where it breaks. Note that this removed some
    > error checking. I also re-ordered the code so that the problem
    > will be more obvious.]
    >
    >
    >>#include <stdio.h>
    >>#include <stdlib.h>

    >
    >
    >>void intMyFunc(int ii)
    >>{
    >> printf("int parameter virtual function (%d)\n",ii);
    >>}
    >>
    >>enum {
    >> VINT,
    >> VSTRING
    >>};
    >>
    >>int main(int argc,char **argv)
    >>{
    >> int ii = 456;
    >>
    >> myFunc(VINT,&ii);

    >
    >


    I don't know the architecture of a Data General Eclipse, however code "like"
    this is running on DG boxes now. I don't understand all the bit diddling the
    DB Eclipse is doing, but perhaps a simple cast to (void *) on the call would
    correct your problem.

    I have just tested the module posted on AIX RISK, v4 and v5, Sun SPARC v6, 7,
    and 9 without failure. Unfortunately, I would need to buy time on my
    development DG boxes, which I have no intention on doing to validate your claims.

    My reply was to provide a hint as to how one could "achieve dynamic
    polymorphism." You have provided a solution for a specific platform which the
    OP may or may not be using, so thank you for your efforts.
    Joseph Dionne, Jan 9, 2006
    #10
  11. mohan

    Jack Klein Guest

    On Mon, 9 Jan 2006 10:16:12 +0530, "mohan" <>
    wrote in comp.lang.c:

    > Hi All,
    >
    > How to implement virtual concept in c.
    >
    > TIA
    >
    > Mohan


    typedef void (*func)(void);

    int main(void)
    {
    func f1 = 0;
    f1();
    }

    f1 is a virtual function, because under the C language standard,
    calling it can do virtually anything.

    --
    Jack Klein
    Home: http://JK-Technology.Com
    FAQs for
    comp.lang.c http://c-faq.com/
    comp.lang.c++ http://www.parashift.com/c -faq-lite/
    alt.comp.lang.learn.c-c++
    http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html
    Jack Klein, Jan 10, 2006
    #11
  12. mohan

    Jack Klein Guest

    On Mon, 9 Jan 2006 11:50:43 +0530, "mohan" <>
    wrote in comp.lang.c:

    > Well I wanted to achieve dynamic polymorphism in c . Ie calling function
    > dynamically
    > depending upon the type
    >
    > Mohan
    >
    > "Default User" <> wrote in message
    > news:...
    > > mohan wrote:
    > >
    > > > Hi All,
    > > >
    > > > How to implement virtual concept in c.

    > >
    > > Tell us what YOU think this means, and why you want to do it in C.
    > >
    > >
    > >
    > > Brian


    First, learn to quote properly. Your reply belongs after the material
    you are quoting. Microsoft did not invent the Internet, and their
    rude manners are unwelcome here. If you use their brain-dead
    newsreader, search the net for a patch to fix it, or move to the
    bottom yourself before adding new text.

    Second, don't. If you want to achieve dynamic polymorphism, use C++.
    That's why Bjarne invented it.

    --
    Jack Klein
    Home: http://JK-Technology.Com
    FAQs for
    comp.lang.c http://c-faq.com/
    comp.lang.c++ http://www.parashift.com/c -faq-lite/
    alt.comp.lang.learn.c-c++
    http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html
    Jack Klein, Jan 10, 2006
    #12
  13. In article <etzwf.4416$>, Joseph Dionne <> writes:
    > Chris Torek wrote:
    > > In article <SOtwf.4257$>
    > > Joseph Dionne <> wrote:
    > >
    > >>Here is a simple example of how you can achieve polymorphisms. ...


    Except on implementations where it will not work, which was Chris'
    point.

    > I don't know the architecture of a Data General Eclipse, however code "like"
    > this is running on DG boxes now.


    Irrelevant. Undefined behavior on one platform says nothing about
    undefined behavior on another.

    > I have just tested the module posted on AIX RISK, v4 and v5, Sun SPARC v6, 7,
    > and 9 without failure.


    Irrelevant. Here we discuss portable C, not what one or five or a
    thousand implementations happen to tolerate.

    > Unfortunately, I would need to buy time on my
    > development DG boxes, which I have no intention on doing to validate
    > your claims.


    No validation is necessary. Chris was kind enough to provide a
    concrete, specific example of a platform where a conforming
    implementation would cause your broken code to misbehave. He could
    just have pointed out that it was broken.

    > My reply was to provide a hint as to how one could "achieve dynamic
    > polymorphism."


    One that invokes undefined behavior, and as such should not pass here
    without comment.

    > You have provided a solution for a specific platform
    > which the OP may or may not be using, so thank you for your efforts.


    No, what Chris provided was an explanation why your code would not
    work on that specific platform; his comment about what would make
    it work was part of that illustration.

    You have this precisely backward. *You* provided a solution which
    is implementation-specific, because it relies on undefined behavior.

    --
    Michael Wojcik

    An intense imaginative activity accompanied by a psychological and moral
    passivity is bound eventually to result in a curbing of the growth to
    maturity and in consequent artistic repetitiveness and stultification.
    -- D. S. Savage
    Michael Wojcik, Jan 12, 2006
    #13
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xiangliang Meng
    Replies:
    2
    Views:
    401
    Jack Klein
    Jun 21, 2004
  2. IK
    Replies:
    2
    Views:
    588
    hemraj
    Jul 23, 2004
  3. Ashwin
    Replies:
    2
    Views:
    332
    Pierre Barbier de Reuille
    Aug 1, 2006
  4. Replies:
    11
    Views:
    675
    James Kanze
    Sep 10, 2006
  5. archimed7592
    Replies:
    4
    Views:
    725
    =?UTF-8?B?UGF3ZcWC?=
    May 30, 2007
Loading...

Share This Page