C++ Inheritance: Derived class pointer to a Base class invokes Derived class method

前端 未结 6 1854
眼角桃花
眼角桃花 2021-01-25 20:28

I am learning C++ inheritance, so I tried this code by creating a Base class dynamically and made a downcast to its Derived class (obviously its not valid to downcast) in order

6条回答
  •  我在风中等你
    2021-01-25 21:06

    first of all, this is no valid downcast. The real type of new parent() indeed is parent and not child. Downcasting is only allowed if the real (also called dynamic) type is child but the pointing object is a parent at the moment.

    The other way around would make more sense. If you create a child and assign it to a parent pointer, this would be fine. But even then: Unless who is virtual the static type instead of the dynamic type decides which function is called.

    Example:

    class parent{
        public:
            void who(){
                cout << "I am parent";
            }
    
        ~virtual parent() {}; // important to have that in class hierarchies where you might use a child that is assigned to a parent pointer!
    };
    
    class child : public parent{
        public:
            void who(){
                cout << "I am child";
            }
    };
    
    int main(){
        parent *c = (parent *)new child();
        c->who(); // output would still be parent because who() is not virtual
        delete c; // important! never forget delete!
        return 0;
    }
    

    If you use, on the other hand,

    virtual void who();
    

    then, the output would be "I am child" like you would expect.

提交回复
热议问题