If these types are related, use a common base class and do the following:
const base& a = (myapp.advanced == true) ? static_cast<base&>(class1()) : class2(); a.something(); a.some_other_thing(); a.yet_another_thing();
The times associated with the const link extend their lifespan to the end of the reference lifetime, so itβs safe. However, you wonβt need such hacking (and you can do away with const if you need to change the object) if you have identified problems creating the object and using it in different functions:
void do_something(base& obj) { obj.something(); obj.some_other_thing(); obj.yet_another_thing(); } if (myapp.advanced == true) { class1 a; do_something(a); } else { class2 a; do_something(a); }
If the types are not bound, you can still do this by turning do_something() into function templates:
template< class T > void do_something(T& obj) { obj.something(); obj.some_other_thing(); obj.yet_another_thing(); } if (myapp.advanced == true) { class1 a; do_something(a); } else { class2 a; do_something(a); }
source share