473,387 Members | 1,621 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

using virtual function in c

Hi All,

How to implement virtual concept in c.

TIA

Mohan
Jan 9 '06 #1
12 2073
"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
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
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
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
*** 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
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
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
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 (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.
Jan 9 '06 #9
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
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
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

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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Roy Yao | last post by:
Hello, I need to pass a pointer to a callback function to the lower level modules. But the function is thought to be a virtual member one. How can I get the real address of the virtual...
19
by: qazmlp | last post by:
class base { // other members public: virtual ~base() { } virtual void virtualMethod1()=0 ; virtual void virtualMethod2()=0 ; virtual void virtualMethod3()=0 ;
8
by: Floogle | last post by:
how do i create a virtual == operator. I've tried the following but it's incorrect... class Interface { ... public: virtual bool operator==(const Interface& rhs)const=0;
0
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen....
6
by: pakis | last post by:
I am having a problem of pure virtual function call in my project. Can anyone explaine me the causes of pure virtual function calls other than calling a virtual function in base class? Thanks
6
by: ivan.leben | last post by:
I want to write a Mesh class using half-edges. This class uses three other classes: Vertex, HalfEdge and Face. These classes should be linked properly in the process of building up the mesh by...
11
by: ypjofficial | last post by:
Hello All, So far I have been reading that in case of a polymorphic class ( having at least one virtual function in it), the virtual function call get resolved at run time and during that the...
4
by: archimed7592 | last post by:
Hi. for example i have base class A and dirved class B: struct A { virtual void f() { std::cout << "A::f()" << std::endl; } }; struct B : public A {
17
by: Jess | last post by:
Hello, If I have a class that has virtual but non-pure declarations, like class A{ virtual void f(); }; Then is A still an abstract class? Do I have to have "virtual void f() = 0;"...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.