Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatically convert list of pointers to derived class to list of pointers to base class

Lets say that I have a base and derived class, and a function that takes an stl vector of pointers to the base class:

class A { public: int x; };

class B : public A { };

void foo(const vector<A*> &va) {
    for (vector<A*>::const_iterator it = va.begin(); it < va.end(); it++)
        cout << (*it)->x << endl;
}

is there any way to pass a list of pointers to the derived class? ie:

vector<B*> vb;
// ... add pointers to vb ...
foo(vb);

The above will cause the following compiler error:

error: could not convert ‘vb’ from ‘std::vector<B*>’ to ‘std::vector<A*>’

Even though B* is convertible to A*.

Finally, if there is a solution for plain pointers, will it work with boost shared pointers as well?

like image 873
Ken Avatar asked Dec 27 '22 16:12

Ken


1 Answers

std::vector<B*> and std::vector<A*> are technically unrelated. C++ does not allow what you want as such.

A way around...Why not have a std::vector<Base*> and insert into it Derived objects? That is the point of polymorphism, dynamic dispatch et al.

like image 67
Science_Fiction Avatar answered Jan 29 '23 04:01

Science_Fiction