From the previous article Properties
of Virtual Functions, we know that a virtual function may or may not
be overridden in the derived lasses. It means, it is not necessary for a derived
class to override a virtual function.
But there are times when a base class is not able to define anything meaningful
for the virtual function in that case every derived class must provide its own
definition of the that function. To force this type of overriding you use the
following general form to declare a virtual function:
virtual ret-type func-name(arg-list)=0;
This type of virtual function is known as Pure Virtual Function.
There are two major differences between a virtual and a pure virtual function,
these are below:
There CAN’T be a definition of the pure virtual function in the base
class.
There MUST be a definition of the pure virtual function in the derived
class.
By making a virtual function ‘Pure’, it becomes necessary for the
derived classes to override it, further since the base class can’t define
a pure virtual function, we can’t have objects of that class. These types
of incomplete classes (having one or more pure virtual function) are known as
Abstract Classes and are used extensively.
The following program illustrates this:
// Pure Virtual Functions
#include <iostream.h>
// base class
class base
{
public:
// pure virtaul function
// declaration
virtual void func() = 0;
// cant define
};
// derived class
class derived : public base
{
public:
// must define
void func()
{
cout<<"Derived1s func()
";
}
};
// main
void main()
{
// --CODE: base b
// wont work because we
// cant have objects of
// absract classes
derived d1;
d1.func();
}
Related Articles:
-
Properties
of Virtual Functions
-
Virtual
Functions and Run-time Polymorphism
-
Introduction
to Virtual Functions
-
-
Static
Member Functions of Class
0 comments:
Post a Comment