B is an A, this is true.
However B* is not an A*. The tricky bit is that B*
can be cast to an A*, but this does not mean it
is an A*.
The reason your original post did not work was because b was being cast to an A* as a
temporary, unnamed object, then that object was passed by non-const reference to a function. This is illegal, because it can do one of two things, and neither one is what you want.
Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class A { };
class B : public A { };
class C : public A { };
void f(A*& a)
{
a = new C; // perfectly legal, C is an A
}
int main()
{
B* b;
f(b); // ?? see notes below
}
|
What would you expect this code to do?
1) In C++, the function call gives you a compiler error for the above reason. You can't pass a temporary object by non-const reference.
or
2) If for some reason the call compiled okay... f() would change
a temporary object and would not be changing 'b' as you'd expect. This would result in runtime errors because the function doesn't do what you expect it to, and also memory leaks in this case because the temporary object can never be deleted.
or
3) If neither of the above happen, and 'b' is changed appropriately... then 'b' now points to a C! But a B isn't a C! Basically it makes 'b' become a bad pointer, and could wreck havok on your program if you tried to dereference it.
1 2 3 4 5
|
void
f (A & bp)
{
bp.print ();
}
|
This code works because a B is an A, so you can pass a B as an A&.
Just remember: B is an A... but a B* is not an A*.