Answer the question
In order to leave comments, you need to log in
C++: Calling different constructors depending on user input?
There is a conditional code that constructs an object in one case with a string, in the other with a number (the bottom line is that it is of different types and, accordingly, calls different constructors):
Foo foo;
if (someFlag)
foo = Foo("SomeString");
else
foo = Foo(42);
Answer the question
In order to leave comments, you need to log in
Variant with generator function:
inline Foo make_foo(bool someFlag)
{
if (someflag)
return Foo("SomeString");
else
return Foo(42);
}
//...
Foo = make_foo(someflag)
1. Own code - make the init function
Foo foo;
if (someFlag)
foo.init("SomeString");
else foo.init(42);
class FooWrap {
public:
FooWrap() : hasFoo(false) {}
void init(int x) { new (fooPlace) Foo(x); hasFoo = true; }
Foo& operator * () { return *reinterpret_cast<Foo*>(fooPlace); }
Foo* operator -> () { return reinterpret_cast<Foo*>(fooPlace); }
~FooWrap() { if (hasFoo) (*this)->~Foo(); }
// Да, и конструктор копирования и op= не забыть — оставлю как упражнение.
private:
char fooPlace[sizeof(Foo)];
bool hasFoo;
}
FooWrap foo;
if (someFlag)
foo.init("SomeString");
else foo.init(42);
foo->doFoo();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question