mercredi 19 février 2020

Why this static cast works? (C++)

i'm studying polymorphic class pointers, i can't understand why (static_cast<B*>(p3->n()))->g();works. I think it should crash because it's trying to point one B* into a C object, but C it's not derived from B, they have the same parent A, but actually they should be different. What's wrong with my argument?

#include <iostream>
using namespace std;

class A {
protected:
    virtual void j() { cout << " A::j "; }
public:
    virtual void g() const { cout << " A::g "; }
    virtual void f() { cout << " A::f "; g(); j(); }
    void m() { cout << " A::m "; g(); j(); }
    virtual void k() { cout << " A::k "; j(); m(); }
    virtual A* n() { cout << " A::n "; return this; }
};

class B : public A {
public:
    virtual void g() const override { cout << " B::g "; }
    virtual void m() { cout << " B::m "; g(); j(); }
    void k() { cout << " B::k "; A::n(); }
    A* n() override { cout << " B::n "; return this; }
};

class C : public A {
private:
    void j() { cout << " C::j "; }
public:
    virtual void g() { cout << " C::g "; }
    void m() { cout << " C::m "; g(); j(); }
    void k() const { cout << " C::k "; k(); }
};

class D : public B {
protected:
    void j() { cout << " D::j "; }
public:
    B* n() final { cout << " D::n "; return this; }
    void m() { cout << " D::m "; g(); j(); }
};

A* p1 = new D(); A* p2 = new B(); A* p3 = new C(); B* p4 = new D(); const A* p5 = new C();

int main() {
    (static_cast<B*>(p3->n()))->g();
    system("PAUSE");
}

Aucun commentaire:

Enregistrer un commentaire