Home > database >  How to instantiate a class from the stack with different constructors?
How to instantiate a class from the stack with different constructors?

Time:11-07

I need to create a class instance from the stack, but depending on a variable I need to call it with different constructors

  class A
    {
     public:
      A(std::string str);
      A(int value)
    };

void main(void)
{
 bool condition = true;

 A class_a {condtion ? "123" : 456};
   
}

But I can't get it to compile.

CodePudding user response:

The ternary operator can't return different types for true and false.

You could solve it like this:

A class_a = condition ? A("123") : A(456);

Other fixes:

#include <string>

class A {
    public:
    A(std::string str) {} // the function must have an implementation
    A(int value) {}       // the function must have an implementation  
};

int main() {              // not void main
    bool condition = true;

    A class_a = condition ? A("123") : A(456);
}
  •  Tags:  
  • c 11
  • Related