C++ : Is there a good way to choose between 2 implementations?
Is there a good way for my header class to choose which .cpp file he can call at runtime?
For example :
a.h
#pragma once
#include <iostream>
class a
{
public:
a() {};
void printA();
};
a.cpp :
#include "a.h"
void a::printA()
{
std::cout << "first";
}
a_mockup.cpp :
#include "a.h"
void a::printA()
{
std::cout << "second";
}
Then in main I want to choose which one I want to call:
main.cpp:
#include "a.h"
#include <string.h>
using namespace std;
int main()
{
a test;
test.printA();
}
Solution 1:
You cannot have two implementations of one function. That would violate the One Definition Rule. You cannot link both translation units into one program.
You can choose between two implementations at link time. If you link the main.cpp translation unit with a.cpp, then you call that implementation, and if you link with a_mockup.cpp, then you call that other implementation.
In order to choose between two functions at runtime, there must be two functions; each with their own name. A minimal example:
void f1();
void f2();
bool condition();
int main()
{
if (condition())
f1();
else
f2();
}
In order to choose between two functions through one interface (i.e. abstraction), you need polymorphism. There are many forms of polymorphism in C++ ranging from function pointers to templates (not runtime) and to virtual functions.