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([co
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]);
AFAIK this can't be done with a reference. You'd have to use a pointer:
MyClass *ptr;
if (condition)
ptr = &object;
else
ptr = &other_object;
The pointer will act similar to a reference. Just don't forget to use ->
for member access.
I usually do this (C++ 11 or later):
std::shared_ptr<ObjType> pObj;
if(condition)
pObj = std::make_shared<ObjType>(args_to_constructor_1);
else
pObj = std::make_shared<ObjType>(args_to_constructor_2);
which is clean and allows using object definition with (possibly different) constructions, a thing you can't do directly with pointers as the compiler will complain from using temporary objects.
In C++, you can't declare a reference without initialization. You must initialize it.