Declare a reference and initialize later?

user1861088 picture user1861088 · Feb 14, 2013 · Viewed 70k times · Source

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?

Answer

Zaffy picture Zaffy · Feb 14, 2013

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]);