0

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

L. F.
  • 19,445
  • 8
  • 48
  • 82
yaodav
  • 1,126
  • 12
  • 34
  • 1
    You can use a `std::vector>` if you want value semantics, i.e., if you want to (logically) store the elements inside the vector instead of filling the vector with references/pointers to externally stored elements, which is error-prone because you are responsible for regulating the lifetime of these elements. – L. F. Feb 19 '20 at 11:20
  • 1
    By the way, please try to avoid `std::endl` when the flushing semantics is not needed. `std::endl` flushes the buffer, while `\n` does not. Unnecessary flushing can cause performance degradation. See [`std::endl` vs `\n`](https://stackoverflow.com/q/213907/9716597). – L. F. Feb 19 '20 at 11:22

0 Answers0