A
A
Ander8132020-09-18 00:56:31
C++ / C#
Ander813, 2020-09-18 00:56:31

Is it possible in C++ to somehow pass the methods of the heir to the parent class?

There is a parent menu class, it has the print_menu() method, which displays the names of menu items (for example, "enter values") from the list, which is defined in the heir, to the console. When a menu item is selected, the function of the heir class that is responsible for it should work.
In python, this could be done using a dictionary.

class AMenu(ABC):
    def __init__(self):
        self.menu_fields = {}

    def print_menu(self):
        for i in self.menu_fields.keys():
            print(i)

class Menu(AMenu):
    def __init__(self):
        self.menu_fields = {"пункт меню 1": self.method1,
                            "пункт меню 2": self.method2}

    def method1(self):
        pass

    def method2(self):
        pass


m = Menu()
m.print_menu()

I tried to solve this problem in C++ using map, but as it turned out in C++, you can't write a class method into a dictionary so easily.
The question actually is whether it is possible somehow in C++ to throw the parent class <the name of the menu item, the function responsible for it>?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2020-09-18
@Ander813

You can immediately think of two options:
1. Virtual methods and inheritance: declare virtual methods in the parent, implement them in the heir. This is the most rigid way to build an architecture, as a result, there is less chance of messing up when refactoring and developing in a large crowd.
2. Functors - softer and looser, less cohesion, more flexible architecture
Depending on the architecture, different tricks with templates may come up, but you need to know the task well.
The general rule is not to drag methods and approaches from other languages ​​into your thinking, even if you like them. This rule appeared immediately after Fortran, alternatives for academic programming began to appear like mushrooms after rain - Pascal in particular.
The anti-pattern sounds like "I write in any programming language like in Fortran, a variation -" I write in C ++ like in C ", and so on.
Programming languages ​​differ in that, in addition to syntax, they also drag along well-established approaches to organizing architecture.

D
Denis Zagaevsky, 2020-09-18
@zagayevskiy

Google "C++ callback"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question