Actually you are lucky. You made two mistakes that caused passing b
to the function fail, while in fact without that other mistakes you can pass b
to the function but it would do the wrong thing silently.
First the two mistakes: B b();
declares a function. To declare a default constructed B
you write B b;
. Then B
inherits privately, hence you cannot convert a B
to an A
. Thats what the error your code causes have told you.
However, after fixing those (and removing user declared constructors taht shouldnt be there when they do nothing)...
class A {};
class B : public A {};
void function(A a) {}
int main(void) {
B b;
function(b); // object slicing !!
}
This code compiles without errors, but usually it does the wrong thing!
Any B
can be converted to an A
because the inheritance is public, but what happens is object slicing: What is object slicing?. If B
had any members not in A
then they would all be lost when passing it to function
. Its not an issue here because neither A
nor B
have any members, but in general you want to avoid objects to get sliced.
TL;DR: References / pointers are needed for polymorphism. Pass by (const
) reference:
void function(const A& a) {} // does not modify a
void function(A& a) {} // modifies a