C++ Abstract classes / Interfaces in C++
By definition, an abstract class in C++ is a class that has at least one pure virtual function (i.e., a function that has no definition). The classes inheriting the abstract class must provide a definition for the pure virtual function; otherwise, the subclass would become an abstract class itself.
* An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.
The following is an example of an abstract class:
class abc
{
public:
virtual void fun1() = 0;
};
Function abc::fun1 is a pure virtual function.
A function declaration cannot have both a pure specifier and a definition.
For example, the compiler will not allow the following:
class abc
{
virtual void g() { } = 0;
};
We cannot have a pure virtual function with body {}.
class abc
{
virtual void fun1() = 0;
};
class xyz: abc
{
void fun1()
{ }
};
* Class abc is an abstract class as it contains a pure virtual function.
* pure virtual function fun1() wil have no body(no definition).
* Class xyz is the derived class of class abc so it is required to have a function with the same name as pure virtual function in base class “abc”
* Derived class “xyz” will have the definition of the function “fun1()”.
* We cannot declare an object of abstract class, if we try to do so an error will get generated .
int main()
{
abc A; //error we cannot declare an object of abstract class
abc *p; //valid we can declare a pointer type object of abstract class
return(0);
}