The C++ language provides virtual
functions. Within the constraints of a pure C language implementation, how can a similar effect be achieved?

- 18,550
- 13
- 57
- 90
-
2why do you want to implement C++ again? Topics like this can be easily found in books and there are lot of online articles as well. By asking these kind of questions, your reputation will be affected and people will start to take you for granted. So do all you can to find the answer, and still can not then ask :). – Ramadheer Singh Jun 24 '10 at 20:20
-
What are you trying to achieve? – Bella Jun 24 '10 at 20:22
-
teacher asked this question to us – Jun 24 '10 at 20:25
-
Please don't ask two different questions in your question. – Lance Roberts Jun 24 '10 at 20:25
-
and he says that there one way that we can do – Jun 24 '10 at 20:25
-
3Sounds like your teacher needs to take a break from academia and get a real programming job. – Matt Davis Jun 24 '10 at 20:26
-
-1: C is not an OOP language and therefore the concept of virtual fonctions is impossible. – Alerty Jun 24 '10 at 20:26
-
he said when we implement phyton in c we use some way ;'if you use same way ,you will achieve' – Jun 24 '10 at 20:34
-
@Alerty, Impossible is nothing: have a look at the source code of GTK+ and you will find a clean way to to this. The language doesn't support it directly but does not forbid it. There are just more responsibilities on developer's side to not break up Object Orientation. – jdehaan Jun 24 '10 at 20:41
-
heyy ,i want to vote down my qustion because it is real one – Jun 24 '10 at 20:47
-
5if this is a not real question why there exits alotof answer,whY??? – Jun 24 '10 at 21:01
-
1I've tried to improve the wording of the question to make it clearer that it could be reopened and get instructive and useful answers. – RBerteig Jun 24 '10 at 21:52
-
+1 This is a good question!, at least in it's current form. – Bill Forster Jun 24 '10 at 22:15
-
To the downvoters: This is a very real-world scenario. There are big companies (for example, Ericsson) that have huge codebases of object-oriented C. – Johan Kotlinski Jun 24 '10 at 23:00
-
@Alerty, that's not true at all. There is nothing at all wrong with this question. Perhaps it is duplicate but save for that is a fine one to be asking. – BobbyShaftoe Jun 25 '10 at 00:21
-
@jdehaan: Yes, you can do something similar to OOP in C and that is called structured programming. – Alerty Jun 25 '10 at 00:50
-
@BobbyShaftoe: The question has been modified since my first comment. – Alerty Jun 25 '10 at 00:51
-
See http://stackoverflow.com/questions/2422970/c-class-object-memory-map/2423091#2423091 – Jun 25 '10 at 01:12
-
1Searching [[c] object oriented](://stackoverflow.com/search?q=[c]+object+oriented) yields: http://stackoverflow.com/questions/3072499/object-oriented-ansi-c-closed http://stackoverflow.com/questions/351733/can-you-write-object-oriented-code-in-c http://stackoverflow.com/questions/1201521/object-oriented-pattern-in-c-closed http://stackoverflow.com/questions/2181079/object-oriented-programming-in-c-closed http://stackoverflow.com/questions/415452/object-orientation-in-c of which the one Roger posted has the best answer to this version of the questions. – dmckee --- ex-moderator kitten Jun 25 '10 at 21:34
-
So-o (Simply object-oriented) - https://www.so-o.org - defines a functional layer which adds an object-oriented programming model to a structured programming language. Inspired by Smalltalk and Objective C, So-o is complete, simple and light, easy to understand. So-o has 3 functions: defclass which defines a new class, sendmsg which is systematically used to send a message to a class or an instance, and supersend which runs a method inherited from a superclass. A game of Poker written in C with So-o : http://www.so-o.org/en/article/poker-in-c. – frasq Jul 27 '18 at 18:52
4 Answers
Stolen from here.
From the C++ class
class A {
protected:
int a;
public:
A() {a = 10;}
virtual void update() {a++;}
int access() {update(); return a;}
};
a C code fragment can be derived. The three C++ member functions of class A
are rewritten using out-of-line (standalone) code and collected by address into a struct named A_functable
. The data members of A
and combined with the function table into a C struct named A
.
struct A;
typedef struct {
void (*A)(struct A*);
void (*update)(struct A*);
int (*access)(struct A*);
} A_functable;
typedef struct A{
int a;
A_functable *vmt;
} A;
void A_A(A *this);
void A_update(A* this);
int A_access(A* this);
A_functable A_vmt = {A_A, A_update, A_access};
void A_A(A *this) {this->vmt = &A_vmt; this->a = 10;}
void A_update(A* this) {this->a++;}
int A_access(A* this) {this->vmt->update(this); return this->a;}
/*
class B: public A {
public:
void update() {a--;}
};
*/
struct B;
typedef struct {
void (*B)(struct B*);
void (*update)(struct B*);
int (*access)(struct A*);
} B_functable;
typedef struct B {
A inherited;
} B;
void B_B(B *this);
void B_update(B* this);
B_functable B_vmt = {B_B, B_update, A_access};
void B_B(B *this) {A_A(this); this->inherited.vmt = &B_vmt; }
void B_update(B* this) {this->inherited.a--;}
int B_access(B* this) {this->inherited.vmt->update(this); return this->inherited.a;}
int main() {
A x;
B y;
A_A(&x);
B_B(&y);
printf("%d\n", x.vmt->access(&x));
printf("%d\n", y.inherited.vmt->access(&y));
}
More elaborate than necessary, but it gets the point across.

- 4,261
- 1
- 20
- 19

- 2,616
- 1
- 16
- 20
-
1+1 Great example: this is about as close as you can get to translating vtables to C and is far more elegant than C programmers doing things like function pointer casts or casting structures of function pointers. It's still bulky and awkward, but hey, C wasn't designed for this. – stinky472 Jun 25 '10 at 01:34
-
1@stinky472: I agree with you, but when someone is at the point of needing code like this it just makes no sense. Certain languages are better suited for certain problems. – Alerty Jun 25 '10 at 04:05
-
Very true, but I have been forced to work in C systems trying to implement OOP. They did it by casting structures with function pointers (like casting struct A), rather than just passing A for polymorphism and allowing every subclass-like struct to simply store A and assign appropriate function addresses and data to it. This, at least, is far more elegant than struct casting or casting function pointers. – stinky472 Jun 25 '10 at 06:25
-
I don't think A::access() is present in the virtual table as this is a non-virt function. – Bandicoot Jun 13 '12 at 06:05
-
-
In `void B_B (B* this)` you are passing a pointer of type `B*` to a function with argument of type `A*`, and assigning `B_functable`, `B_vmt` to `A_functable`, `this->inherited.vmt`, without expicit casting nor error, how's that possible? (i.e it is not possible: it gets underlined as an error even before compilation). – Ziezi Jun 21 '17 at 12:41
@GCC....A virtual function is declared in the Base class of an object and is then "overriden" or implemented in the sub classes. i.e., say you have Vehicle Base class and you create two sub-classes, Motorcycle and, Automobile. The Base class would declare a virtual function of AddTires() Then the Sub Classes would implement this function and each sub class would implement it differently. A car has 4 wheels, where a motorcycle has 2. I can't give you the syntax for C or C++, though. Hope this helps

- 9,149
- 25
- 93
- 132
Here is a description of what virtual functions are.
There is no way to implement virtual functions in plain C, because C has no notion of inheritance.
Update: As is discussed in the comments below, it is possible to do something similar to virtual functions in straight C using structures and function pointers. However, if you are accustomed to a language like C++ that has "true" virtual functions, you will probably find the C approximation far less elegant and harder to use.

- 43,959
- 6
- 69
- 99
-
1actually, there is a notion of inheritance in C but it does not respect ACCESS control here : http://stackoverflow.com/questions/577465/in-c-can-i-derive-a-class-from-a-struct – Ramadheer Singh Jun 24 '10 at 20:25
-
-
2You can't do it directly (class is missing :)) - but it's no problem to implement such a system using structures and function pointers. – ManniAT Jun 24 '10 at 20:31
-
Note that it is (usually) possible to interoperate with C++ virtual functions from C, if enough is known about the C++ ABI. For example, Windows COM uses virtual functions to declare interfaces, and there is a technique (made just barely usable by a lot of macros) for declaring COM interfaces and calling through them from C. Also, C++ started life (with many of its current features including virtual functions) as a preprocessor that read C++ text and wrote C. So it *is* possible to implement them in C, just not pleasant. – RBerteig Jun 24 '10 at 20:32
-
That question is on C++ which has inheritance. All you can do in C is simulate it by storing pointers to your functions on the structures you're passing around. – jer Jun 24 '10 at 20:37
-
he said when we implement phyton in c we use some way ;'if you use same way ,you will achieve' – Jun 24 '10 at 20:39
-
@RBerteig: but, of course, there is no standard C++ ABI, so any C code which gets cozy with C++ virt funcs will be unportable. So if you want a portable, dynamically-linkable virtual function interface (like COM), you have to at least act like you're using C. – Tim Schaeffer Jun 24 '10 at 20:40
-
-
@Tim, true. And COM was defined in a way that "coincidentally" allowed an Interface to be represented as an array of pointers to functions in C and as a virtual function table in Visual C++. This was acceptable because portability was not a priority for Microsoft. But remains an example of one way that virtual functions can be implemented in and called from C. – RBerteig Jun 24 '10 at 21:48
-
@Gollum: It is possible in C to have functions in structs. One has to use a function pointer and set it (this would be rather ugly). Also, please note that there is no public/private/protected keyword in C. In C++, a struct is the same as a class except that everything is public by default. – Alerty Jun 25 '10 at 03:57
Virtual functions are a feature of C++'s object orientation. They refer to methods that depend on a specific object instance rather than what type you're currently carrying them around as.
In other words: if you instantiate an object as Bar, then cast it to Foo, virtual methods will still be the ones they were at instantiation (defined in Bar), while other methods will be the ones from Foo.
Virtual functions are typically implemented by way of vtables (that's for you to do more research on ;)).
You can simulate similar things in C by using structs as poor man's objects and saving function pointers in them.
(More correctly, non-virtual functions make it ambiguous which class the method should be taken from, but in practice I believe C++ uses the current type.)

- 17,870
- 3
- 59
- 51