Tuesday, April 24, 2007

Concept of virtual function and abstract class

Virtual Function


There are two types of binding. They are static and dynamics binding. Static binding is a function call matches with the correct function definition at compile time, thus use the base class function, and not the derived class ones.

However, for virtual function, the compiler matches a function call with the correct function definition at run time, which is dynamic binding. The keyword "virtual" is declared before the name of a member function. Therefore, if the function in the derived class is the same as the virtual function of the base class, and is being called, it overrrides the virtual function.

Take note, if the derived class has a function with the same name as the virtual function in the base class, BUT has different number of parameters in the paretheses, THEN it cannot overrides the virtual function.

In additional, virtual functions can be a friend to another class, but cannot be global or static, because it must be a member function of a base class, which relies on a specific object to determine which implementation of the function is called.

Lastly about virtual function, it must be one of the following:
(1) Defined
(2) Declared pure
(3) Defined and declared pure

A base class containing one or more pure virtual member functions is called an abstract class.....



Abstract Class


Normally, an abstract class is used as a base class. It must have at least one pure virtual function using a pure specifier (= 0) in the declaration of a virtual member function. In additional, there is no such thing as pure virtual function declaration in class, having both the pure specifier and its definition.

An abstract class cannot be used as a parameter type and a function return type. For example, virtual void test() is correct. You can, however, declare pointers and references to an abstract class.

Lastly, since virtual member functions are meant to be inherited, a class derived from an abstract base class will also be abstract, not until you override each pure virtual function in the derived class. This means we cannot instantiate an abstract class, unless the virtual functions are being overriden by the derived class.


File

http://www.geocities.com/pikagaming/Monster_Class.zip

No comments: