A pure virtual function is distinguished by the fact that it has no definition, and the heading of the function has the notation "= 0".
Here is an example of how a pure virtual function in C++ would look:
class AbstractClass { public: virtual void pure_virtual() = 0; // a pure virtual function // note that there is no function body };
Although the "= 0" appended to the end of the virtual function definition may look like the function is being assigned a value of 0, that is not true. The notation "= 0" is just there to indicate that the virtual function is a pure virtual function, and it has no body.
Any base class that contains a pure virtual function is abstract, and cannot have an instance of itself created. This also means that any class that derives from that base class must override the definition of the pure virtual function in the base class, and if it doesn't then the derived class becomes an abstract class as well.
In Java, pure virtual methods are declared using the abstract keyword. Such a method cannot have a body. A class containing abstract methods must itself be declared abstract. But, an abstract class is not necessarilly required to have any abstract methods. An abstract class cannot be instantiated.
In C++, a regular, "non-pure" virtual function provides a definition, so it doesn't mean that the class that contains it becomes abstract. You would want to create a pure virtual function when it doesn't make sense to provide a definition for a virtual function in the base class itself. Use a regular virtual function when it makes sense to provide a definition in the base class.
No comments:
Post a Comment