Re: sequence of inheritance from virtual base class?
{ Please do not insert blank lines when quoting. Inserted blank lines
in quoted section removed -mod/we }
On Tuesday, May 14, 2013 7:33:48 PM UTC+2, Ralf Fassel wrote:
I have a problem with the sequence of inheritance:
// header1.h
class Base {
public:
Base() {}
virtual ~Base() {}
virtual void foo() = 0;
};
// header2.h
#include "header1.h"
class Unrelated1 {};
class Unrelated2 {};
class Derived1 : public Base, public Unrelated1, public Unrelated2 {
public:
Derived1() {}
~Derived1() {}
void foo() {}
};
class Derived2 : public Unrelated1, public Unrelated2, public Base {
public:
Derived2() {}
~Derived2() {}
void foo() {}
};
// main.cc
// g++ -o main main.cc
#include "header2.h"
int main() {
Derived1 d1;
Derived2 d2;
d1.foo(); // ok
d2.foo(); // crashes in big app
}
The problem seems to be the sequence of inheritance: if I inherit
from 'Base' first (Derived1), the code seems to run ok. If I
inherit from 'Base' last (Derived2), the code crashes reliably at
runtime in a seemingly unrelated code position (other class, other
function, but always the same).
The crash happens when Derived2 comes from one shared lib, Derived1
from another. Calling a non-virtual function in Base seems ok, the
crash happens only when calling a virtual function in Base, so it
looks to me like a wrong lookup in the virtual function table.
First note that you're outside standard C++, who knows nothing about
shared libraries (or other kinds thereof). So it could be that your
issue is somehow related to the way code is built.
As for inheritance order, it does not matter, I don't think so. BTW,
if it did, your test code would also fail.
The fact code crashes elsewhere, in practice, indicates that the
problem is elsewhere. Note also that the code you've shown only reads
memory, so it's really improbable that it somehow provokes a crash
elsewhere.
I would try running with valgrind or the debug version of the MS CRT
and wait for memory corruption error reports - are you doing this? I
would also debug and look at the state of your variables at the place
of the crash - did you try that? (Can you simulate in debug builds,
BTW? If not, i would build an unoptimized release build and try to
have a look at the crash dump).
HTH,
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]