C ++ Polymorphism

Some books say that a class that declares or inherits a virtual function is called a polymorphic class.

Class B does not have virtual functions, but more than one passes - this is a test.

Class C has one virtual function, but does not inherit.

class A {}; class B : public A {}; class C { public: virtual void f () {} }; 

is class B or C polymorphic?

+6
source share
3 answers

2003: 10.3/1 clearly indicates:

A class that declares or inherits a virtual function is called a polymorphic class.

You said it yourself, literally, so I really don’t understand what the question is.

C (and its descendants, if you add them) are polymorphic; A and B are not.


Note that in the broader sense of OOP, you can always perform some “polymorphism” in that C ++ always allows you to speed up; thus, all objects that inherit can be considered as different (but related) types.

However, the term “polymorphic” is somewhat different in C ++, where it has more in common with whether it can also be flushed down. If you don't want to be misled like the C ++ standard, you can call this "dynamic polymorphism."

+8
source

In the standard, "A class that declares or inherits a virtual function is called a polymorphic class."

Since neither A nor B declares or inherits a virtual function, they are not polymorphic. C declares a virtual function, so it is polymorphic.

+3
source

class C is polymorphic, which means that using dynamic_cast or typeid in C& will perform runtime type checking, and member functions through C& or C* will use virtual send.

(Of course, the as-if rule allows the compiler to avoid scheduling during execution of some condition when it knows in advance the type of execution, for example, when you just created an object.)


As mentioned in a comment by @Bill, this is not what some books say, it is a definition of a polymorphic class found in the C ++ standard (section 10.3, [class.virtual] ):

Virtual functions support dynamic binding and object-oriented programming. A class that declares or inherits a virtual function is called a polymorphic class.

+2
source

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


All Articles