-1
for (AbstractThingy abstractThingy : ABSTRACT_THINGIES) {
    abstractThingy.doStuff();
}

Compiler is saying that abstractThingy is instantiating AbstractThingy, but I didn't instantiate I'm just looping

I then tried AbstractThingy& abstractThingy, but it gave the same error elsewhere.

pete
  • 1,878
  • 2
  • 23
  • 43

1 Answers1

1

I found out in C++ we can't have vectors of abstract classes. It needs to be a vector of pointers to it. As a workaround I've simply converted the abstract class into a fake abstract class which throws an exception if I try to directly use the method that's supposed to be overridden by a subclass.

Edit: As noted by commenters the workaround wouldn't work, so I converted it to a vector of pointers. After learning about std::unique_ptr instead of raw pointers it was not as much of a hassle as I thought. Only gotcha moment was for (std::unique_ptr<AbstractThingy>& abstractThingy : ABSTRACT_THINGIES), you need the ampersand there to prevent it from making copies which would throw another compile error. Also, when instantiating the object via std::make_unique it should be std::make_unique<ChildClassOfAbstractThingy> rather than std::make_unique<AbstractThingy>

pete
  • 1,878
  • 2
  • 23
  • 43
  • 1
    your workaround is broken. A `std::vector` can only hold instances of `FakeAbstractClass>` not instances of derived types. Read https://stackoverflow.com/questions/274626/what-is-object-slicing – 463035818_is_not_an_ai Dec 02 '21 at 18:27
  • That would surprise me because it compiled. Is the behavior going to be unexpected and if so in what way? – pete Dec 02 '21 at 18:28
  • Oh poop, I guess when running it it would probably default to the base class's implementation of doStuff() – pete Dec 02 '21 at 18:34
  • code that compiles but is still wrong should not surprise you. Try `int main() { int x = 1/0; }`. The explanation is in the link – 463035818_is_not_an_ai Dec 02 '21 at 18:34
  • 1
    See a question with answers [here](https://stackoverflow.com/q/2160920/509868) for more inspiration. Note: some outdated 10-years-old info there, but also valuable up-to-date info. – anatolyg Dec 02 '21 at 18:39