Declaring an object before initializing it in c++

Quantum7 picture Quantum7 · Apr 29, 2009 · Viewed 46k times · Source

Is it possible to declare a variable in c++ without instantiating it? I want to do something like this:

Animal a;
if( happyDay() ) 
    a( "puppies" ); //constructor call
else
    a( "toads" );

Basially, I just want to declare a outside of the conditional so it gets the right scope.

Is there any way to do this without using pointers and allocating a on the heap? Maybe something clever with references?

Answer

Greg Hewgill picture Greg Hewgill · Apr 29, 2009

You can't declare a variable without calling a constructor. However, in your example you could do the following:

Animal a(happyDay() ? "puppies" : "toads");