Search code examples
c++segmentation-faultvirtual

Virtual functions on classes derived form structs


I have a class that derives from a C struct. The class does not do anything special, other than initialization in the constructor, deinitialization function during the destructor, and a few other methods that call into C functions. Basically, it's a run-of-the-mill wrapper. Using GCC, it complained that my destructor was not virtual, so I made it that. Now I run into segfaults.

/* C header file */
struct A
{
  /* ... */
}

// My C++ code
class B : public A
{
public:
  B() { /* ... init ... */ }
  virtual ~B() { /* ... deinit ... */ }

  void do()
  {
    someCFunction(static_cast<A *>(this));
  }
};

I was always under the assumption that the static_cast would return the correct pointer to the base class, pruning off the virtual table pointer. So this may not be the case, since I get a segfault in the C function.

By removing the virtual keyword, the code works fine, except that I get a gcc warning. What is the best work around for this? Feel free to enlighten me :).


Solution

  • Both the explicit and implicit conversion to A* are safe. There is neither need for an explicit cast, nor is it going to introduce vtables anywhere, or anything like that. The language would be fundamentally unusable if this were not the case.

    I was always under the assumption that the static_cast would return the correct pointer to the base class, pruning off the virtual table pointer.

    Is absolutely correct.

    The destructor need be virtual only if delete ptr; is called where ptr has type A*- or the destructor invoked manually. And it would be A's destructor that would have to be virtual, which it isn't.

    Whatever the problem is in your code, it has nothing to do with the code shown. You need to expand your sample considerably.