Consider we have to write classes for animals which displays their voices.
We will require different classes for different animals.
But there are a lot of features which are same across these animals.
We keep all these similar features in a single class, like a template and extend this class for specific animals.
Interfaces also work in a similar manner.
An interface is a class which acts as a base class for other derived classes.
It does not have its own object implementation.
Interfaces are implemented using abstract classes.
Abstract classes are the classes which contain at least one pure virtual function.
We already know what a virtual function is.
A pure virtual function is the one which only has a declaration.
A pure virtual function is declared by assigning a value 0 to a virtual function.
virtual return_type functionName() = 0;
Awesome!!! Let’s see how we can write an interface.
An interface is a class which acts as a base class for other derived classes.
Writing an Interface
An interface is written exactly like a class.
The keyword class is used to declare the interface.
Remember, we need at least one pure virtual function inside the class.
Let’s write a simple interface Student containing a pure virtual function name().
class Student{
public:
virtual void name() = 0;
};
Wow! That was easy. Isn’t it?
Now, we can inherit the interface Student and have multiple definitions for function name().
Remember the syntax to write a derived class from a base class?
Let’s see how.
class Student{
public:
virtual void name() = 0;
};
class Rahul: public Student{
public:
void name(){
cout<<“Rahul”;
}
};
We have written a class Rahul containing the definition for name() function which inherits class Student.
In a similar way, we can write more classes inheriting the base class Student and implementing the function name().
An interface can be inherited in the same way as the class.
class Student{
public:
virtual void name() = 0;
};
class Rahul: public Student{
public:
void name(){
cout<<“Rahul“;
}
};
int main() {
Rahul ra; //object of type Rahul
ra.name(); //Calling function name()
}
Can you guess the output of the above snippet?
The output will be
Rahul
Great! We have learnt a lot. Now let’s put this knowledge to test.
To Summarize
A pure virtual function is a virtual function assigned the value 0.
An interface is a class which acts as a base class for other derived classes.
Interfaces are implemented using abstract classes.
Abstract classes are the classes which contain at least one pure virtual function.
A pure virtual function is declared by assigning a value 0 to a virtual function.