Created
October 19, 2020 16:21
-
-
Save shaardie/9a749ffe85cad5a5cf9de20d23619ecc to your computer and use it in GitHub Desktop.
C++ Interface Example for mocking Hardware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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