I want to create an std::vector<A&>
and fill it with elements of class B
and C
, which derive from A
.
struct A {
virtual void print (){std::cout << "A" <<std::endl;}
};
struct B : public A {
void print (){std::cout << "B" <<std::endl;}
};
struct C : public A {
void print (){std::cout << "C" <<std::endl;}
};
int main()
{
B b;
C c;
std::vector<A&> vec{b,c};
for(auto &e : vec)
{
e.print();
}
return 0;
}
I know it can be done with ptr but my question if for reference