lundi 29 juin 2020

dynamic_cast<> question using Stroustrup example

I'm testing a dynamic_cast<> example in Stroustrup C++ 4th Ed Page 642 and it does not compile. I'm using the following picture directly from the book trying to learn how it works. Does anyone know if this is Eratta (its not in his published errata doc) or I have misread something?

Stroustrup Graphic, dashed line represents protected: Page 642 graphic

#include <iostream>
using namespace std;

// H = Ival_box
class H {
};

// G = Ival_slider
class G : public H {
};

// I = BBwindow
class I {
};

// F = BB_slider
class F : public I {
};

// X = BB_ival_slider
class X : public G, protected F {
};


int main(int argc, char *argv[])
{
    // works
    X xx{};
    if (auto p = dynamic_cast<G*>(&xx))
        cout << "X*...G*" << endl;

    // works
    G gg{};
    if (auto p = dynamic_cast<H*>(&gg))
        cout << "G*...H*" << endl;

    // compilation error, 'I' is not polymorphic
    I ii{};
    if (auto p = dynamic_cast<H*>(&ii))
        cout << "I*...H*" << endl;

    return 0;
}

Compilation and results:

clang++ -std=c++11 -pedantic -Wall test164.cc && ./a.out
test164.cc:31:18: error: 'I' is not polymorphic
    if (auto p = dynamic_cast<H*>(&ii))
                 ^                ~~~
1 error generated.

Compilation and results with error commented out:

clang++ -std=c++11 -pedantic -Wall test164.cc && ./a.out
X*...G*
G*...H*

Aucun commentaire:

Enregistrer un commentaire