Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class.
Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends with = 0
. Here is the syntax for a pure virtual function,
virtual void f() = 0;
Below we have a simple example where we have defined an abstract class,
//Abstract base class
class Base
{
public:
virtual void show() = 0; // Pure Virtual Function
};
class Derived:public Base
{
public:
void show()
{
cout << "Implementation of Virtual Function in Derived class\n";
}
};
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
Implementation of Virtual Function in Derived class
In the above example Base class is abstract, with pure virtual show() function, hence we cannot create object of base class.
When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.
// Abstract base class
class Base
{
public:
virtual void show() = 0; //Pure Virtual Function
};
void Base :: show() //Pure Virtual definition
{
cout << "Pure Virtual definition\n";
}
class Derived:public Base
{
public:
void show()
{
cout << "Implementation of Virtual Function in Derived class\n";
}
};
int main()
{
Base *b;
Derived d;
b = &d;
b->show();
}
Implementation of Virtual Function in Derived class