reinterpret_cast vector of derived class to vector of base class

前端 未结 1 1980
既然无缘
既然无缘 2021-01-22 09:10

I have a 3rd-party class, say, class A, and a function accepting vector of class A from the same 3rd-party, say f3() (See simplified progr

相关标签:
1条回答
  • 2021-01-22 09:16

    To answer the question from your code :

    No, it's actually a very bad practice , and it will lead to undefined behavior.

    If sizeof(A) is equal to sizeof(B) your code might end up working ,considering that all functions derived in B and used inside f3 are virtual and non inline.

    If you end up using such code , make sure you will never ever add another virtual function / member variable to the B class .

    If you want a way to bypass this limitation (f3 third party function only accepts vector of A ) , try making B a composite rather then a derived (if you are not accessing protected members of A ) :

    class A 
    {
       public:
       int n;
       void f1();
    }
    class B
    {
      public:
          B (const A& a); // dependency injection
          void f2();
          A  myA; // bad practice, should be private with getter /setter
    }
    

    This way you are isolating the A specific functionality / features.

    Ofc you will still need to manually make a vector of A objects made from the objects contained in B (you cannot pass a vector of B).

    0 讨论(0)
提交回复
热议问题