Here is some code that illustrates the question:
#include <iostream>
class Base {
};
class Derived : public Base {
};
void doThings(Base* bases[], int length)
{
for (int i = 0; i < length; ++i)
std::cout << "Do ALL the things\n";
}
int main(int argc, const char * argv[])
{
Derived* arrayOfDerived[2] = { new Derived(), new Derived() };
doThings(arrayOfDerived, 2); // Candidate function not viable: no known conversion from 'Derived *[2]' to 'Base **' for 1st argument
// Attempts to work out the correct cast
Derived** deriveds = &arrayOfDerived[0];
Base** bases = dynamic_cast<Base**>(deriveds); // 'Base *' is not a class
Base** bases = dynamic_cast<Base**>(arrayOfDerived); // 'Base *' is not a class
// Just pretend that it should work
doThings(reinterpret_cast<Base**>(arrayOfDerived), 2);
return 0;
}
Clang produces the errors given in the comments. The question is: "Is there a correct way to cast arrayOfDerived
to something that doThings
can take?
Bonus marks:
- Why does clang produce the errors "
'Base *' is not a class
" on the given lines? I know thatBase*
isn't a class it's a pointer. What is the error trying to tell me? Why hasdynamic_cast
been designed so that indynamic_cast<T*>
the thingT
must be a class? - What are the dangers of using the
reinterpret_cast
to force everything to work?
Thanks as always :)