An interface class is an abstract class which contains all pure virtual functions. For example:
class IMovable
{
public:
virtual void left() const = 0;
virtual void right() const = 0;
virtual void move() const = 0;
virtual void stop() const = 0;
};Here, IMovable is an interface class which other classes has to implement the virtual functions.
Interface classes are usually prefixed with I as done in the example above.
Following shows a comprehensive example on the interface classes:
#include <iostream>
#include <string>
#include <string_view>
class ILogger
{
public:
virtual void log(std::string_view msg) const = 0;
};
class FileLogger : public ILogger
{
public:
void log(std::string_view msg) const override
{
std::cout << "Saving log to file: " << msg << '\n';
}
};
class RemoteLogger : public ILogger
{
public:
void log(std::string_view msg) const override
{
std::cout << "Sending log to remove server: " << msg << '\n';
}
};
void doSomeTask(ILogger *logger)
{
std::cout << "Doing something" << '\n';
logger->log("Done!");
}
int main(int argc, char const *argv[])
{
FileLogger logger;
doSomeTask(&logger);
RemoteLogger r_logger;
doSomeTask(&r_logger);
return 0;
}