The following code
#include <iostream>
using namespace std;
class A {};
class B : public A {};
class C : public B {};
void foo(A *a) {
cout << 'A' << endl;
}
void foo(B *b) {
cout << 'B' << endl;
}
int main() {
C *c = new C[10];
foo(c);
}
compiles fine and prints 'B' as expected.
But when I change the main()
function to
int main() {
C c[10];
foo(c);
}
I get a compiler error saying
test_arr.cpp: In function 'int main()':
test_arr.cpp:23:10: error: call of overloaded 'foo(C [10])' is ambiguous
test_arr.cpp:23:10: note: candidates are:
test_arr.cpp:11:6: note: void foo(A*)
test_arr.cpp:15:6: note: void foo(B*)
Why is it ambiguous now? I thought an array was always just a pointer so I don't really see the difference.
Edit:
I just realized the whole code I posted was a bad idea to start with: As soon as you add data members to the classes and access them in the foo
functions you will run into problems, as explained here, since the foo(B*)
function has no way of knowing it's actually dealing with C
objects which potentially take more memory space. So don't do this!
Nevertheless I am still interested in understanding why the compiler complains about ambiguity here, since I really don't see a problem with that here.