Question

I'm working in C++14 and trying to figure out a way to put two classes (with the same name) inside the same header file. In this scenario one class would always be ignored as a result of something happening in main.cpp during runtime. Here's an example of this header file:

// First class:
class foo
{
public:
    foo();
private:
    int var;
};

foo::foo()
{
    var = 1;
}

// Second class:
class foo
{
public:
    foo();
private:
    int var;
};

foo::foo()
{
    var = 2;
}

So let's say during runtime the user entered "1". Then the first definition of class foo would be used, and the compiler would ignore the second class. But then if the user enters "2", the first class is ignored and the second class is used.

I know it's ugly, but in my specific case it saves a ton of work.

Was it helpful?

Solution

Technically, it's possible

You can give two different classes the same name, by putting each class in separate namespaces:

namespace space_1 {
    class foo { ... }; 
}  

namespace space_2 {
    class foo { ... }; 
}

This defines two different and unrelated classes: space_1::foo and space_2::foo.

You may then define at compile time which namespace to use in the using context (in main(), or in a configuration header):

int main() {
    using namespace space_1; 
    foo a; 
}

If you want to choose either the one or the other at run time, you'll have to either use explicit scope resolution, or use the class and the defined object in a limited scope using a namespace:

if (a) {
    using namespace space_1; 
    foo f; 
    // do smething with f HERE 
}
else {
    using namespace space_2; 
    foo f; 
    // do something else with f HERE
}

But does it make sense ?

Using different namespaces for classes with the same name is typically used for managing compile-time library dependencies, for example:

  • avoiding name conflicts between different components.
  • new version of a library with a different interface.
  • choice of alternative libraries (e.g. boost::xxx vs. std::xxx).

It is a very bad idea to use this construct for a different purpose, such as choosing the class implementations at runtime.

Is there a better design ?

If you have a class with a well defined API, but need to cope with different variants/implementations at run time, you may consider polymorphism:

  • Make foo an abstract base class, and create a derived class for every needed variant.
  • Use a factory to instantiate the objects with the right derived class.

Alternatively, you may redesign your foo class, so that it requires a parameter in the constructor (i.e. the initial value of var in your case) or inject a strategy in the constructor.

Licensed under: CC-BY-SA with attribution
scroll top