简体   繁体   中英

C++ delete a class pointer & polymorphism

I am learning about polymorphism, and this is something I have stumbled on. I cant find satisfying answer and testing the following code doesnt yield expected result.

#include <stdio.h>
#include <iostream>

class Base {
    public:
        Base(){
            std::cout<<"Constructing Base" << std::endl;
        };
        virtual int get_a(){
            return p_a;
        };
        virtual int check(){
            std::cout<<"check Base" << std::endl; return 2;
        };
        virtual ~Base(){
            std::cout<<"Destroying Base" << std::endl;
        };
        int p_a = 4;
};

class Derive: public Base {
    public:
        Derive(){
            std::cout<<"Constructing Derive" << std::endl;
        };
        int get_a(){
            return p_a;
        };
        int check(){
            std::cout<<"check Derive" << std::endl;
            return 3;
        };
        ~Derive(){ std::cout<<"Destroying Derive" << std::endl; };
        int p_a = 2;
 };

int main() {
        Base *basePtr = new Derive();
        delete basePtr;
        basePtr->check();
        std::cout << "p_a: " << basePtr->get_a() << std::endl;
        return 1;
}

Console output :

Constructing Base    // line 1
Constructing Derive  // line 2
Destroying Derive    // line 3
Destroying Base      // line 4
check Base           // line 5
p_a: 4               // line 6

I see why I get line 1-4, the basePtr is pointer to Derive, which inherits from Base, which implements virtual functions.

My 1. expectation : After calling delete , the pointer basePtr should not be able to deliver the function call ->check(), and also there should be no value p_a.

My 2. expectation : I would expect the value p_a from Derive (p_a = 2), to appear on the output, because basePtr stores the pointer of Derive.

Could someone correct my thinking ?

This is undefined behavior. Whatever results you get, are invalid.

delete basePtr;

This destroys the object.

basePtr->check();

After destroying the object, the shown code attempts to dereference a pointer to the destroyed instance of the class, and invoke a method of the destroyed object. Invoking a method of a destroyed object is undefined behavior.

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