Monday, July 27, 2009

What are the difference between a virtual function and a pure function(c++)?

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.





///

What are the difference between a virtual function and a pure function(c++)?
Well, both are related to inheritance.





Virtual functions are the ones which are declared in a base class and defined in derived classes. Virtual functions may be defined in the base class as well.


Use the keyword virtual to define such functions;


virtual int fun( );





Pure virtual functions are not defined in the base class, they are only defined in (all) the derived classes. You can declare a pure virtual function as:


virtual void fun( ) = 0;





When a base class has a pure virtual function, it cannot be used to instantiate any objects. It becomes an abstract class.


No comments:

Post a Comment