-1

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();
} 
Upgrade
  • 95
  • 6
  • 2
    Easier and more idiomatic IMO would be to have interface, and then `A` and `MockupA` would inherit from that interface. – Jarod42 Jan 13 '22 at 16:29
  • Currently, you can build 2 applications, and use appropriate cpp file for each one. Mostly depends of your build system for the details. – Jarod42 Jan 13 '22 at 16:30
  • 1
    This seems to resemble an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Are you asking how to choose from two functions, or are you asking how to make all of this code compile and link? (You can't.) – Drew Dormann Jan 13 '22 at 16:31
  • Runtime polymorphism using derived types? – Robert Harvey Jan 13 '22 at 16:33
  • 1
    It depends whether the choice has to done at build time (choose which module to link into the executable) or at run time (use polymorphism). – Serge Ballesta Jan 13 '22 at 16:36
  • In other programs I've used that use DI, they have an IoC manager which is the part that plumbs up the available object that implements an interface to the interface that needs to be fulfilled by having that dependency injected. The ones I've used are for C# (Unity, Autofac, Ninject). I'm not aware of an off-the-shelf general purpose IoC manager/coordinator for C++, you may have to write one yourself. – Eljay Jan 13 '22 at 16:39

1 Answers1

3

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326