I have a reference to MyOjbect
, but the the exact object depends on a condition. So I want to do something like this:
MyObject& ref;
if([condition])
ref = MyObject([something])
else
ref = MyObject([something else]);
I cannot do this right now because the compiler does not allow me to declare but not initialize a reference. What can I do to achieve my goal here?
You need to initliaze it. But if you would like to conditionally initialize it, you can do something like this:
MyObject& ref = (condition) ? MyObject([something]) : MyObject([something else]);