Polymorphism c++
In some books there is written that class that declares or inherits a virtual function is called a polymorphic class.
Class B doesn't have any virtual functions but passe开发者_StackOverflow社区s more than one is-a test.
Class C has one virtual function but doesn't inherit.
class A {};
class B : public A {};
class C
{
public:
virtual void f () {}
};
is class B or C polymorphic ?
2003: 10.3/1
states, clearly:
A class that declares or inherits a virtual function is called a polymorphic class.
You actually said this yourself, word-for-word, so I don't really understand what the question is.
C
(and its descendants, if you add any) is polymorphic; A
and B
are not.
Note that, in a wider OOP sense, you can always perform some "polymorphism" in that C++ always allows you to upcast; thus all objects that inherit can be treated as a different (but related) type.
However, the term "polymorphic" is defined slightly differently in C++, where it has more to do with whether you can downcast as well. If you don't want to be confusing like the C++ standard, you might call this "dynamic polymorphism".
Per the standard, "A class that declares or inherits a virtual function is called a polymorphic class."
Because neither A
nor B
declare or inherit a virtual function, they are not polymorphic.
C
declares a virtual function, so it is polymorphic.
class C
is polymorphic, meaning that using dynamic_cast
or typeid
on a C&
will do a runtime type check, and calling member functions through a C&
or C*
will use virtual dispatch.
(Of course, the as-if rule allows the compiler to avoid the runtime dispatch under some condition when it knows the runtime type in advance, such as when you just created the object.)
As @Bill mentioned in a comment, that isn't just what some books say, it's the definition of 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.
精彩评论