You have it backwards! The problem being that in C++, the parent-child relationship is one way. Or in other words it's an IS-A relationship.
Basically this means that while children classes can take place of parents, i.e. you can pass a sedan
to an automobile
vector, you can't go backwards. Because not every automobile
is a sedan
.
Your function definition should be void myFunc(Child *c) {...}
if you ONLY want to take the child class, but if you want to take ANY child of the parent, or the parent itself, then do it like: void myFunc(Parent *p) {...}
instead.
Also as a small sidenote, I suggest using references instead of pointers whenever possible. See here for more discussion.
Addendum:
I want to use function overloading to define different behaviour for different types of Childs for myFunc. Any Idea how I can do this?
In order to accomplish this you can use templates and use specialization like so:
#include <iostream>
class automobile {
};
class sedan : public automobile {
};
template <typename T>
void foo(T& t) {
std::cout << "An automobile!" << std::endl;
}
template <>
void foo<sedan>(sedan& t) {
std::cout << "A sedan!" << std::endl;
}
int main() {
automobile a;
sedan s;
foo<automobile>(a);
foo<sedan>(s);
}
And the output as expected is:
An automobile!
A sedan!