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.