What you are looking for is called a subtype polytype; in C ++, only reference types allow polymorphic virtual function calls to work as you expect. You can use the link:
void print_function(base& item){ item.print(); }
Or a pointer:
void print_function(base* item){ item->print(); }
What you did is pass the object by value, copying only part of the base object - this is called slicing:
void print_function(base item){ item.print(); }
Note that since your print() member function does not modify the object, it can and should be declared const . In addition, (void) in parameter lists is a C style and redundant in C ++; use () instead.
virtual void print() const { cout << "Base" << endl; }
const is part of the signature, so subclasses should also indicate it:
virtual void print() const override { cout << "inherit_a" << endl; }
Then print_function() can take a reference to the const object:
void print_function(const base& item){ item.print(); }
Or a pointer to a const object:
void print_function(const base* item){ item->print(); }
In this document, print_function() also does not change its argument.
source share