Tuesday, 21 August 2012

What is a pure virtual function in C++ and abstract methods in JAVA?

A pure virtual function contains only method signature without any body( i.e., no implementation)
Example of pure virtual function in C++

class AbstractClass {
   virtual void pure_virtualfunction() = 0;  // a pure virtual function - no body

Here "=0" may seems like 0 is assigned to the function, that is not true. It only indicates that the virtual function is pure virtual function and it has no body

Any base class that contains pure virtual function is abstract and cannot have an instance itself created and it also means that any class derived from the base class must override the definition of pure virtual function in the base classm if it doesn't, then derived class becomes 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 java we declare the class as abstract under two cenarios:
1) when the class contains abstract methods whose implementation will be provided later by its sub-  class.
2) whenever we don't want the object of a class to be created as sub-most object then we declare the class as abstract even if it doesn't contains any abstract methods.
EX: javax.servlet.http.HttpServlet class is declared as abstract even it doesn't contain any abstract methods.
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.
this link helped me  http://www.programmerinterview.com/index.php/c-cplusplus/pure-virtual-function/

No comments:

Post a Comment