Implementing virtual concept in c

M

mohan

Hi All,

How to implement virtual concept ( dynamic polymorphism ) in c.
I guess i should create a void pointer which is pointing to the function.
Not clear about this
Does anyone have some idea

Mohan
 
J

Jim Langston

Alf P. Steinbach said:
* mohan:

Don't use void pointers: you lose type checking, i.e. you introduce bugs.



See <url:
http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf>,
section 1.2 on "Run-time polymorphism".

He said C, not C++.

I've seen something similar to polymorphism done in C with function
pointers. Although it didn't use void pointers, which are a bad thing, but
function pointers.

I may have the syntax off on this.

typedef (void MyFunc*)(int, float);

Which should (check syntax) create a function pointer called MyFunc which
points to a function returning a void taking 2 parameters, int and float.
Then you can at run time point this pointer to different functions depending
on what you want to do.

void MyRealFunc( int SomeInt, float SomeFloat)
{
std::cout << "In MyRealFunc" << std::endl;
}

void MyRealFunc2( int SomeInt, float SomeFloat)
{
std::cout << "In MyRealFunc2" << std::endl;
}

int main()
{
MyFunc = MyRealFunc;
MyFunc(1, 2.0);
MyFunc = MyRealFunc2;
MyFunc(1, 2.0);

return 0; // Not needed in main
}

Although this concept only works for functions, not classes as it would in
C++.

Thinking about it, I wonder if you couldn't create a pointer to a structure,
and the structure could have variables and function pointers itself
emulating C++'s class.
 
A

Alf P. Steinbach

* Jim Langston:
He said C, not C++.

I know. That discussion is meant to show how to do this at the C level. If
it doesn't, then I'd be grateful for feedback so that I can fix it.

Cheers,

- Alf
 
J

Jack Klein

Hi All,

How to implement virtual concept ( dynamic polymorphism ) in c.
I guess i should create a void pointer which is pointing to the function.
Not clear about this
Does anyone have some idea

1. Posts about C are off-topic here.

2. Why?

3. There is absolutely no defined conversion between void pointer and
any sort of function pointer in either C or C++.

4. If you want dynamic polymorphism, use C++. You must know it
exists, you found this group.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top