Why should you put “virtual” in the base class instead of just using “overriding” in children? in c ++

The title pretty much says it all. Why do you need to define in the base class that you can override the function in the future?

Thus, you need to change the base class if you want to get different behavior from it, and you did not think about this particular function in the database to mark the virtual one.

As far as I know, you solve such a definition of abstraction in java using an override that (although I only look at java so far) seems to me more natural. Is this a twist in C ++ to get programmers to think, or is there a technical reason why this works this way?

+4
source share
2 answers

This is done so that the decision to create a virtual member function remains with the base class.

The decision to create a virtual function has design implications: if you create a virtual function, you must consider the possibility of its execution in a different way. On the contrary, you can expect that a non-virtual function will remain invariant.

Permission overrideto force virtuality "outside" may violate the assumptions of the author of the function. In addition, this will complicate a separate compilation, because the C ++ compiler must do additional things for virtual functions that are not performed for non-virtual ones, for example, finding an effective address from vtable or another mechanism used to implement virtual sending.

, Java , . ++ , . Java , Object, ++ , .

+6

++ 20, "interface" ( )

0

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


All Articles