Yes, there is no C++ interface keyword available. To create interface in C++ program, we use pure virtual functions into a class. Generally, we prefix class name with letter “I” as naming convention e.g. “class IMyClass”, to depict Interfaces in c++.
Note that in an interface, we keep only pure virtual functions and we never provide implementation of functions in it. Derived/Extended classes are responsible to implement these pure virtual functions, or we can say that only derived classes have implementation of c++ interfaces.
C++ Interface class example:
class ILogin{
public:
virtual void name () = 0;
virtual void password () = 0;
};
How to create interface and use it in C++ program?
Lets see how to implement and create c++ interface. In below c++ interface inheritance example, we have an interface called ILogin that contains 2 pure virtual functions name() and password(). Also, there are two extended classes that is EmailLogin and MembershipLogin classes. These two derived classes will inherit and implement interface class pure virtual functions.
Note that how C++ interface has been used in client i.e. main() method.
class ILogin{
public:
virtual void name () = 0;
virtual void password () = 0;
};
class EmailLogin:public ILogin
{
public:
void name (){
cout<<"Email Login name"<<"\n";
}
void password (){
cout<<"Email password"<<"\n";
}
};
class MembershipLogin :public ILogin
{
public:
void name (){
cout<<"Membership Login name"<<"\n";
}
void password (){
cout<<"Membership password"<<"\n"; }
};
Now, lets see how to use interface class in c++ program. Here is the main() function that will use the interface class and functions in a program.
int main() {
//Email login
ILogin *email = new EmailLogin(); email->name();
email->password();
//Members login
ILogin *members = new MembershipLogin();
members->name();
members->password();
if(email) delete email;
if(members) delete members;
return 0;
}