How to implement virtual functions in C??
How to implement virtual functions in C??
You can't do virtual functions in C.
Now if you mean C++ its a different story.
No. I mean virtual functions in C.
We can implement classes in C too. Since there is no compiler support for classes in C, you need to program in such a way that it works like a class.
Normal C (IE not object C) doesn't not support overloading functions, nor can you write "classes". The closest you can come is using Abstract Data Type discipline.
you can write class in C.
The compiler internally passes the object by reference as the first argument for every member function.
example:
say you have a class,
class X{
int funcX(int y); // internall treated as int funcX( X& t, int y);
};
now while calling the funcX,
X xobject;
xobject.funcX(10);
internally, the compiler uses funcX( xobject, 10) to call the function. All these is hidden from the user.
Using the concept above, it is possible to implement classes in C.
A C compiler does not know how to do any of that. You can write an ADT using a struct but that is a discipline and not a compiler forced abstraction. Also as I said you can not (save C99 which I'm not 100% sure about) use function overloading in C. The closes you could come is:
C Does not have references it knows nothing about OO programming ideas. And since you want to do this in C it really should be in the C forum.Code:struct Foo { int bar; }; struct Foo * add ( struct Foo *f, const struct Foo *b ) { f->bar += b->bar; return f; }
It is possible, if your name is Bjarne Stroustrup. C++ was originally written in C.... Well, this reference says C++ was written in C++... Ah, recursion... gives me a headache!
[EDIT]Which language did you use to write C++?
The first C++ compiler (Cfront) was written in C++. To build that, I first used C to write a "C with Classes"-to-C preprocessor. "C with Classes" was a C dialect that became the immediate ancestor to C++. That preprocessor translated "C with Classes" constructs (such as classes and constructors) into C. It was a traditional preprocessor in that it didn't undestand all of the language, left most of the type checking for the C compiler to do, and translated individual constructs without complete knowledge. I then wrote the first version of Cfront in "C with Classes".
For those that dont' know, Mr. Stroustrup created the C++ language.
[/EDIT
Last edited by DougDbug; 11-19-2004 at 01:04 PM.
sangi, you seem to know how to implement classes in C, so try understanding how vtables work and implement something similar to that in order to get the equivalent of virtual functions.