How could one implement C++ virtual functions in C [duplicate]
Asked Answered
E

4

21

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

Eightfold answered 24/6, 2010 at 20:20 Comment(20)
why 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 :).Eagle
What are you trying to achieve?Living
teacher asked this question to usEightfold
Please don't ask two different questions in your question.Rowdyism
and he says that there one way that we can doEightfold
Sounds like your teacher needs to take a break from academia and get a real programming job.Pressroom
-1: C is not an OOP language and therefore the concept of virtual fonctions is impossible.Mcgee
he said when we implement phyton in c we use some way ;'if you use same way ,you will achieve'Eightfold
@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.Rapprochement
heyy ,i want to vote down my qustion because it is real oneEightfold
if this is a not real question why there exits alotof answer,whY???Eightfold
I've tried to improve the wording of the question to make it clearer that it could be reopened and get instructive and useful answers.Eskilstuna
+1 This is a good question!, at least in it's current form.Ellord
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.Guinna
@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.Igor
@jdehaan: Yes, you can do something similar to OOP in C and that is called structured programming.Mcgee
@BobbyShaftoe: The question has been modified since my first comment.Mcgee
See https://mcmap.net/q/659988/-c-class-object-memory-map/…Cherice
Searching [[c] object oriented](://stackoverflow.com/search?q=[c]+object+oriented) yields: #3072999 #352233 #1202021 #2181579 https://mcmap.net/q/46160/-object-orientation-in-c of which the one Roger posted has the best answer to this version of the questions.Pumpkinseed
So-o (Simply object-oriented) - 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 : so-o.org/en/article/poker-in-c.Rafaelof
E
34

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.

Elicia answered 24/6, 2010 at 20:27 Comment(6)
+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.Sexivalent
@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.Mcgee
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.Sexivalent
I don't think A::access() is present in the virtual table as this is a non-virt function.Bussell
Just a note: the link in the beginning is broken.Hacksaw
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).Hacksaw
B
1

@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

Bronez answered 24/6, 2010 at 20:28 Comment(1)
Of course, my answer is based on C# and that object modelBronez
P
0

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.

Prohibitive answered 24/6, 2010 at 20:22 Comment(10)
actually, there is a notion of inheritance in C but it does not respect ACCESS control here : #577965Eagle
@Gollum: A C++ struct is not like C struct.Mcgee
You can't do it directly (class is missing :)) - but it's no problem to implement such a system using structures and function pointers.Pewit
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.Eskilstuna
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.Insipience
he said when we implement phyton in c we use some way ;'if you use same way ,you will achieve'Eightfold
@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.Elicia
@Alerty, really ? I did not know that can you elaborate?Eagle
@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.Eskilstuna
@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.Mcgee
K
0

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.)

Kelikeligot answered 24/6, 2010 at 20:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.