Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare one object to be of multiple classes, depending on a condition

Tags:

c++

This question is based on Create objects in conditional c++ statements.

However, in my case I need to declare one object from a choice of multiple classes which will then be passed as argument to a function. Hence, the object has to be declared with a pre-defined name (obj in this case).

Class1 obj;
Class2 obj;

if (...) {
  obj = Class1(); }
if (...) {
  obj = Class1(a, b); }
else
  obj = Class2();

// Do something on declared object
DoSomething(obj.variable_);

Currently the above will not work because of conflicting declaration of obj. How should I go about doing this?

like image 250
nasw_264 Avatar asked Sep 16 '25 16:09

nasw_264


1 Answers

You might not need std::variant, if your object doesn't have to be "polymorphic" at run-time. Refactor your code to:

if (...) {
  DoSomething(Class1());
if (...) {
  DoSomething(Class1(a, b));
else
  DoSomething(Class2());

And make DoSomething a template or overload set:

void DoSomething(const Class1&) { }
void DoSomething(const Class2&) { }
like image 139
Vittorio Romeo Avatar answered Sep 19 '25 07:09

Vittorio Romeo