By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,682 Members | 1,980 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,682 IT Pros & Developers. It's quick & easy.

using virtual function in c

P: n/a
Hi All,

How to implement virtual concept in c.

TIA

Mohan
Jan 9 '06 #1
Share this Question
Share on Google+
12 Replies


P: n/a
"mohan" <mo**********@in.bosch.com> 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) ks***@mib.org <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.
Jan 9 '06 #2

P: n/a
On 2006-01-09, mohan <mo**********@in.bosch.com> 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.
Jan 9 '06 #3

P: n/a
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
Jan 9 '06 #4

P: n/a
Well I wanted to achieve dynamic polymorphism in c . Ie calling function
dynamically
depending upon the type

Mohan

"Default User" <de***********@yahoo.com> wrote in message
news:42*************@individual.net...
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

Jan 9 '06 #5

P: n/a
*** top-posting corrected ***
mohan wrote:
"Default User" <de***********@yahoo.com> 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/>
Jan 9 '06 #6

P: n/a
Chuck F. wrote:
*** top-posting corrected ***
mohan wrote:
"Default User" <de***********@yahoo.com> 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);
}
Jan 9 '06 #7

P: n/a
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
Jan 9 '06 #8

P: n/a
In article <SO*****************@newsread1.news.atl.earthlink. net>
Joseph Dionne <jd*****@hotmail.com> 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 (4039.22'N, 11150.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.
Jan 9 '06 #9

P: n/a
Chris Torek wrote:
In article <SO*****************@newsread1.news.atl.earthlink. net>
Joseph Dionne <jd*****@hotmail.com> 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.
Jan 9 '06 #10

P: n/a
On Mon, 9 Jan 2006 10:16:12 +0530, "mohan" <mo**********@in.bosch.com>
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/~a...FAQ-acllc.html
Jan 10 '06 #11

P: n/a
On Mon, 9 Jan 2006 11:50:43 +0530, "mohan" <mo**********@in.bosch.com>
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" <de***********@yahoo.com> wrote in message
news:42*************@individual.net...
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/~a...FAQ-acllc.html
Jan 10 '06 #12

P: n/a

In article <et*****************@newsread1.news.atl.earthlink. net>, Joseph Dionne <sp******@mindspring.com> writes:
Chris Torek wrote:
In article <SO*****************@newsread1.news.atl.earthlink. net>
Joseph Dionne <jd*****@hotmail.com> 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 mi************@microfocus.com

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
Jan 12 '06 #13

This discussion thread is closed

Replies have been disabled for this discussion.