0

My code:

#include <array>

struct Base {};

struct Derived : Base {};

void f_one(Base & foo) {}

void f_array(std::array<Base, 2> foo) {}

int main() {
  Derived a;
  f_one(a);
  std::array<Derived, 2> b = {};
  f_array(b);
  return 0;
}

My error:

no known conversion from 'array<Derived, [...]>' to 'array<Base, [...]>' for 1st argument

Why is the compiler able to convert a single instance of Derived to Base but not an std::array of them?

  • 7
    While `Derived` is-a `Base`, the same is relationship is not true of containers of `Derived` and `Base`. `Derived` and `Base` will likely have different sizes, for example, thus the offsets will be completely wrong when iterating the array. – user4581301 Apr 26 '23 at 23:46
  • 5
    Side note: When you cast a `Derived` into a `Base`, [you slice the object](https://stackoverflow.com/q/274626/4581301). If you want to use polymorphism you need to work with references to objects, not the objects themselves. – user4581301 Apr 26 '23 at 23:49
  • 1
    About terminology: the compiler does not **cast** a `Derived` to `Base`. It **converts** it. A cast is something you write in your source code to tell the compiler to do a conversion. – Pete Becker Apr 27 '23 at 00:14
  • 1
    The next question is question is likely "Why can't I pass `std::array` to `std::array &`, but that resolves down to the same thing, the containers are different types After that comes "Why can't pass `std::array` to `std::array &`?" This one annoys me a bit because it's references all across the board now (pointers in the case of the arrays because you can't have arrays of references since references aren't objects), but it's blocked because of [stuff like this](https://isocpp.org/wiki/faq/containers#container-ptr-conversion). – user4581301 Apr 27 '23 at 00:14
  • Somebody has to have a good duplicate for this, but I'm struggling to find it. – user4581301 Apr 27 '23 at 00:21
  • @user4581301 Is it good enough? – 273K Apr 27 '23 at 00:48
  • It will do. I'd like more meat on the why, but the proposed solution is solid. – user4581301 Apr 27 '23 at 17:25

0 Answers0