Static_pointer_cast <Derived> pReallyABase = static_pointer_cast <Derived (pBase) works! What for?

I do not understand why this works. pReallyABase is a downstream shared_stream, Derived>, which points to an instance of the base class.

I understand why the compiler allows me to call pReallyABase-> onlyForDerived () since I defined it as a pointer to a derived class, but why don't I get a run-time error when I try to call a derived function of the class using this pointer?

class Base { 
    public:
        virtual string whatAmI() {
            return "I am a Base";
        }
};

class Derived : public Base {
    public:
        virtual string whatAmI() {
            return "I am a Derived";
        }

        string onlyForDerived() {
            return "I can do Derived things";
        }
};


int main(int argc, char *argv[]) { 
    shared_ptr<Base> pBase = shared_ptr<Base>(new Base);
    shared_ptr<Derived> pReallyABase = static_pointer_cast<Derived>(pBase);

    cout << pReallyABase->whatAmI() << endl;
    cout << pReallyABase->onlyForDerived() << endl;  //Why does this work?
    return 0;
}

results

I am a Base
I can do Derived things
+4
source share
2 answers

, - ( ) ++, " ++" :

++ , - , . -. . invocations : :

obj.magnitude();

magnitude_7Point3dFv(&obj);

ptr->magnitude();

magnitude_7Point3dFv(ptr);

, onlyForDerived - Derived, . undefined, .

+2

undefined, Base Derived, , , .

, "", Derived, , .

, (undefined is undefined). , , , , , , , .

+2

All Articles