0

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.

K-RAN
  • 896
  • 1
  • 13
  • 26
  • 5
    Virtual functions are the least of your worries. Do you have [a good introductory C++ book](http://stackoverflow.com/questions/388242/the-definitive-c++-book-guide-and-list)? If not, you should get one; it is all but impossible to learn to write correct C++ code without one. – James McNellis Jan 29 '11 at 21:43
  • Nope, and I know that I need to get one asap, but for now this is a more pressing worry of mine. I figured that I should ask a question on here while looking into which reference to buy (thanks for the link). – K-RAN Jan 29 '11 at 21:47
  • To clarify: this code is so completely broken that you should delete it, get one of the introductory books named in the aforementioned list, and start from scratch. There is nothing salvageable in this code. (Maybe that sounds harsh, but it's the truth: continuing forward with the code you have will only lead to further pain and suffering.) – James McNellis Jan 29 '11 at 22:19
  • Thanks...I was just thinking that lol. – K-RAN Jan 29 '11 at 22:58

3 Answers3

2

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. virtual functions only affect classes in the same inheritance hierarchy. In your case, there is no relationship between A and B, so A's doStuff is always going to get called.

Your segfault is probably caused because b is a really a B, but assigned to an A*. When the compiler sees b->doStuff, it tries to go to a vtable to look up which version of doStuff to call. However, B doesn'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.

class NormalClass
{
      int a;
      double b;

 public:
      NormalClass(int x, double y);
};

looks like this:

+------------------------------------+
| a (4 bytes) | b (8 bytes)          |
+------------------------------------+

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:

 class ClassWithVTable
 {
      int a;
      double b;

   public:
       ClassWithVTable();
       virtual void doSomething();
 };

is laid out in memory like this:

  +-----------------------------------------------------------+
  | vptr (sizeof(void *)) | a (4 bytes) | b (8 bytes)         |
  +-----------------------------------------------------------+

and vptr points to an implementation-defined table called the vtable, which is essentially an array of function pointers.

Daniel Gallagher
  • 6,915
  • 25
  • 31
1

Casting a B * to an A * and then attempting to dereference it via a member function call is undefined behaviour. One possibility is a seg-fault. I'm not saying that this is definitely the cause, but it's not a good start.

I don't understand why you're not using inheritance here!

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • it's for a hw assignment and we're not allowed to use it. Trust me, if we were allowed to use inheritance, I'd be done by now haha – K-RAN Jan 29 '11 at 21:57
  • @K-RAN: Your code is basically C, not C++! This seems a pretty silly assignment... – Oliver Charlesworth Jan 29 '11 at 21:58
  • This is just the first part of 2. The second part is more C++ STL oriented. I still need to get through with this first part though. – K-RAN Jan 29 '11 at 22:02
  • 1
    @K-RAN: Well, what you have above will cause undefined behaviour. I don't know what the assignment question is, but this won't be the solution. – Oliver Charlesworth Jan 29 '11 at 22:04
0

For polymorphic objects, the pointer to the vtable is stored inside the object.
So at runtime, the method to be actually called is found via dereferencing and jumping into the vtable.
In your case you cast B * to A *.
Since A is polymorhic, the method call will be determined via the vtable, but since the object being used is actually B the vpointer used, is actually garbage and you get the segfault.

Cratylus
  • 52,998
  • 69
  • 209
  • 339