No Virtual constructors but virtual destructor

前端 未结 3 612
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 17:19

If we dont have virtual constructors then why we have virtual destructors? Can constructors also be virtual?

3条回答
  •  眼角桃花
    2021-02-06 18:01

    Virtual destructors are needed because at destruction time, you don't always know what type you're dealing with:

    Base *make_me_an_object()
    {
        if (the_moon_is_full())
            return new Derived();
        else
            return new Base();
    }
    
    int main()
    {
        Base *p = make_me_an_object();
        delete p;
    }
    

    The delete in the above program's main doesn't know whether its p points to a Base or a Derived object, but if the Base destructor is virtual (as it should be), then delete can use *p's vtable to find the right destructor.

    By contrast, at construction time, you always know what kind of object you're creating. (And in case you don't, then you can create a factory or "virtual constructor" that does know.)

提交回复
热议问题