0

Sorry for the confusing title. Hopefully an example will clear things up. I have a base class called Renderable like this:

class Renderable {
public:
    virtual void render() = 0 ;
};

I plan to iterate through an std::vector of references of derived classes of Renderables. Like this:

std::vector<Renderable&> allRenderables = //passed in somewhere;
for (Renderable& renderable : allRenderables) {
    renderable.render();
}

I compiled and this is what I get:

Error C2528: <template-parameter>: pointer to reference is illegal

I tried deleting & but it tells me that Renderable is abstract. Also, I think this is a poor way to implement things.

Could someone please tell me what I got wrong? Or is this the right way to implement this at all?

I thank you in advance!

  • You cannot allocate abstract classes, hence why you cannot use something like `std::vector`. Either provide a definition for `render()` inside the `Renderable` class or have a derived class provide its definition and use that class instead. In case of `std::vector`, you cannot store references inside `std::vector` since references are not objects, but you can use something like [`std::vector>`](https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper) or even `std::vector.` – Ruks Jul 05 '21 at 02:08
  • References don't really exist. They're nothing more than an alternate name, an alias, for an existing variable, so you can't take the address of one. – user4581301 Jul 05 '21 at 02:09
  • @Ruks This seems to be what I am looking for. Thank you! – Minh To Quang Jul 05 '21 at 02:21

0 Answers0