Using Inheritance for Common Functions

I am trying to create a template class with several children that override template methods (I believe that I did it right). Then I need one function that can work with all child elements.

For instance:

#include <iostream> using namespace std; class base{ public: virtual void print(void){ cout << "Base" << endl; } }; class inherit_a : public base{ public: virtual void print(void) override{ cout << "inherit_a" << endl; } }; class inherit_b : public base{ public: virtual void print(void){ cout << "inherit_b" << endl; } }; void print_function(base item){ item.print(); } int main(){ inherit_a item_a; print_function(item_a); return(0); } 

This prints the "base", as you would expect, however I would like to use the print method inherit_a or the method inherit_b print if inherit_b was inherit_b to print_function . Is this possible?

+1
source share
3 answers

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.

+4
source

The problem is that you take a base value before print_function . Even if you pass an instance of inherit_a , it causes the creation of a new object that is typed at base (called a slice of objects). At print_function , this is no longer the value of inherit_a and therefore will not call the derived method.

What you are looking for is a base reference to prevent slicing and allow you to maintain the value of your original type

 void print_function(base& item){ item.print(); } 
+1
source

"Is something like that possible?" - Yeap, and it's called polymorphism .

0
source

Source: https://habr.com/ru/post/1469298/


All Articles