Copy constructor needs to call a method that depends on the object, but constructor can't be virtual

后端 未结 6 630
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 19:24

I have an abstract base class with two inherited classes. In both these classes I define a virtual method that is used by the constructor. Now I need to create a copy constr

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 20:25

    We'd have to know exactly what you are trying to achieve to know what the right solution is.

    However there is no problem in calling a virtual function on the object being copied, as that is already a fully constructed object. You can also feed the "this" into it, as long as that function knows that the pointer being passed in is not fully constructed yet. Thus:

    T::T( const T & other )
    {
       other.some_virtual_method(this); // legal but potentially dangerous
    }
    
    void T::some_virtual_method( T* other ) const
    {
       other->another_virtual_method(); // dangerous in this situation
    }
    

提交回复
热议问题