Skip to content

Instantly share code, notes, and snippets.

@shaardie
Created October 19, 2020 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaardie/9a749ffe85cad5a5cf9de20d23619ecc to your computer and use it in GitHub Desktop.
Save shaardie/9a749ffe85cad5a5cf9de20d23619ecc to your computer and use it in GitHub Desktop.
C++ Interface Example for mocking Hardware
#include <iostream>
using namespace std;
/**
* @brief Base Class
*
*/
class Interface
{
public:
/**
* @brief pure virtual function providing the interface.
*
* @return string
*/
virtual string run() = 0;
};
/**
* @brief Hardware fulfilling the interface
*
*/
class Hardware : public Interface
{
public:
string run()
{
return "Hardware";
}
};
/**
* @brief Test fulfilling the interface,
* but e.g. do nothing with actual hardware
*/
class Test : public Interface
{
public:
string run()
{
return "Test";
}
};
/**
* @brief Example class using the interface
*/
class Caller
{
public:
/**
* @brief Reference to the interface
*/
Interface &m_interface;
/**
* @brief Construct a new Caller object
*
* @param intf interface reference for the Caller
*/
Caller(Interface &intf) : m_interface(intf){};
/**
* @brief Call the interface
*/
void run()
{
cout << "Calling " << m_interface.run() << endl;
}
};
int main(void)
{
// Contructing the actual hardware object, give it to the caller and call it
Hardware hw;
Caller c_hw(hw);
c_hw.run();
// Contructing the test object, give it to the caller and call it
Test t;
Caller c_t(t);
c_t.run();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment