I have structs like this:
struct A
{
int a;
virtual void do_stuff(A*a)
{
cout << "I'm just a boring A-struct: " << a << endl;
}
}
struct B
{
A a_part;
char * bstr;
void do_stuff(B*bptr)
{
cout << "I'm actually a B-struct! See? ..." << bptr->bstr << endl;
}
}
B * B_new(int n, char * str)
{
B * b = (B*) malloc(sizeof(struct B));
b->a_part.a = n;
b->bstr = strdup(str);
return b;
}
Now, when I do this:
char * blah = strdup("BLAAARGH");
A * b = (A*) B_new(5, blah);
free(blah);
b->do_stuff(b);
I get a segfault on the very last line when I call do_stuff and I have no idea why.
This is my first time working with virtual functions in structs like this so I’m quite lost. Any help would be greatly appreciated!
Note: the function calls MUST be in the same format as the last line in terms of argument type, which is why I’m not using classes or inheritance.
You’re mixing a C idiom (embedded structs) with C++ concepts (virtual functions). In C++, the need for embedded structs is obviated by classes and inheritance.
virtualfunctions only affect classes in the same inheritance hierarchy. In your case, there is no relationship betweenAandB, soA‘sdoStuffis always going to get called.Your segfault is probably caused because
bis a really aB, but assigned to anA*. When the compiler seesb->doStuff, it tries to go to a vtable to look up which version ofdoStuffto call. However,Bdoesn’t have a vtable, so your program crashes.In C++, a class without virtual functions that doesn’t inherit from any other classes is laid out exactly like a C struct.
looks like this:
However, a class (or struct) with virtual functions also has a pointer to a vtable, which enables C++’s version of polymorphism. So a class like this:
is laid out in memory like this:
and
vptrpoints to an implementation-defined table called thevtable, which is essentially an array of function pointers.