简体   繁体   中英

dynamic_cast fails when cast a derived class to base class

In Primer c++ 5th

降价

class A {
    public:
        A() : a(1) {}
        virtual ~A() = default;
    private:
        int a;
};
class B : public A {
    public:
        B() : b(2) {}
    private:
        int b;
};
class C : public B {
    public:
        C() : c(3) {}
    private:
        int c;
};
//class D : public B, public A {                   cause error
//    public:
//        D() : d(4) {}
//    private:
//        int d;
//};

int main()
{

    //A *pa = new C;
    //B *pb = dynamic_cast<B*>(pa);          //1st case
    B *pb = new B;
    C *pc = dynamic_cast<C*>(pb);        //2nd case
    cout << pc << endl;
    //A *pa = new D;
    //B *pb = dynamic_cast<B*>(pa);        //3rd case
}
//output: 0     cast failure

Q1:

Here in the above code .I can understand why the 2nd case doesn't work, but the type of pb-pointed object is B which is the public base class of C .And this is the 2nd situation of what's said in Primer c++.
So why the 2nd case doesn't work while primer c++ said this kind of cast will succeed?

Q2:

the 3rd case. Errors occurred during compilation

error: ‘A’ is an ambiguous base of ‘D’

What does this error mean?

in your second example you create a class B, B is a base class for C.

so you can't cast a base class to some derived class.

this will work:

 B *pb = new C();
 C *pc = dynamic_cast<C*>(pb);

regarding 3rd example D derive from B and A, but B also derive from A, this make problems for compiler. you try to derive 2 times for A, the compiler will not know what function A to use, the base A or the derived version of B. al

you should read more about base and derived classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM