Polymorphism is the ability of a pointer or reference to a base class type to behave in different ways when it is used to manipulate objects of different subtypes of that base class. The first requirement for polymorphism is that the objects must be accessed via pointer or reference. A second requirement for polymorphism to work is that the methods whose polymorphic behavior is desired must be declared as virtual. Overridden methods not declared as virtual will behave correctly only for statically bound objects.For base class pointers or references bound to objects during execution, polymorphism will not be seen if a method is not declared virtual. That means that the base class method will be used rather than the subclass method even if the subclass overrides the method.
Virtual Functions
Any base class method intended to be overridden in any subclass should be declared as virtual.
Virtual is optional, but recommended in subclasses
Polymorphism in C++ works only with pointers and references and only with methods declared as virtual.
If a class declares any virtual methods, the destructor of the class should be declared as virtual as well. This ensures that regardless of the actual subclass of an object accessed via a base class pointer or reference, the correct destructor will clean it up.
In Java, all methods are virtual by default.
class BaseClass
{
virtual void functionName();
virtual ~BaseClass() {}
};
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment