protected and private inheritance interferes with properoperation of dynamic_cast

Darin Adler darin@eazel.com
Wed Nov 17 21:12:00 GMT 1999


The following test program fails with gcc.

The version I used was gcc version 2.95.2 19991024 (release).
The system I tested on was a Pentium III PC, running Linux (Red Hat 6.1).

I've also reproduced this same bug with older versions of gcc on the same
machine.

The command line I used to build was: "g++ demonstrate_dynamic_cast_bug.cc".
Here is the source file:

    extern "C" int puts(const char*);

    class Base
    {
    public:
        virtual void f() {}
    };

    class Derived : public Base
    {
    };

    class MoreDerived : protected Derived
    {
    public:
        Base* as_base() { return this; }
    };

    int main()
    {
        MoreDerived md;
        Base* bp(md.as_base());
        if (dynamic_cast<Derived*>(bp))
            puts("test succeeded");
        else
            puts("test failed");
    }

The test should write "test succeeded", but instead writes "test failed".
Somehow, the fact that MoreDerived inherits from Derived using protected
inheritance rather than public inheritance results in a failure of the
dynamic cast on the object from Base* to Derived*, when the object type is
MoreDerived.

This same test program works fine with some other compilers that I've tried.

    -- Darin



More information about the Gcc-bugs mailing list