c++ - reinterpret_cast vector of derived class to vector of base class -


i have 3rd-party class, say, class a, , function accepting vector of class a same 3rd-party, f3() (see simplified program below).

for easier use of a, created derived class b. many part of program used class b.

the question is, how can call f3() vector of b argument? forced casting in argument of f3() program below practice?

#include <vector> #include <iostream> #include <algorithm>  using namespace std;  // 3rd-party class class { public:     int n;     void f1(); };  // class class b: public { public:     void f2(); };  // 3rd-party function void f3(std::vector<a> &a);  int main() {     std::vector<b> y;      y.push_back(b());     y.push_back(b());     y.push_back(b());     y.push_back(b());      f3(*(vector<a>*)(&y));  // practice?     cout << y[3].n << endl;     return 0; } 

note that, compatibility, purposely make class b have no more variables class a, when b inherits a. however, class b have more methods a.

will guarantee sizeof(a) same sizeof(b), our cast of vector work?

i working on c++03

to answer question code :

no, it's bad practice , , lead undefined behavior.

if sizeof(a) equal sizeof(b) code might end working ,considering functions derived in b , used inside f3 virtual , non inline.

if end using such code , make sure never ever add virtual function / member variable b class .

if want way bypass limitation (f3 third party function accepts vector of ) , try making b composite rather derived (if not accessing protected members of ) :

class  {    public:    int n;    void f1(); } class b {   public:       b (const a& a); // dependency injection       void f2();        mya; // bad practice, should private getter /setter } 

this way isolating specific functionality / features.

ofc still need manually make vector of objects made objects contained in b (you cannot pass vector of b).


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -