即使派生对象不存在,派生的基指针也能工作

时间:2018-03-03 16:59:01

标签: c++

我有一个简单的问题。据我所知,如果变量范围结束,则变量将被销毁。但是在下面的情况下,即使Derived被破坏,基指针仍然会调用派生的虚函数。是不是很幸运,或者Derived对象实际上不会被销毁,直到Derived的所有引用/指针都没有被销毁?

int main(int argc, char **argv) {

    Base *base_ptr;

    std::string value = "hello";

    if ( value == "hello")
    {
        Derived der1;
        base_ptr = &der1;

    }
    else {
        DerivedNew der_new;
        base_ptr = &der_new;
    }

    base_ptr->printDerived();
    // this prints the virtual function of the derived object. I was hoping it to print the base object.
}

0 个答案:

没有答案