Search code examples
c++scopedeclarationinstantiation

Declaring an object before initializing it in c++


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?


Solution

  • You can't do this directly in C++ since the object is constructed when you define it with the default constructor.

    You could, however, run a parameterized constructor to begin with:

    Animal a(getAppropriateString());
    

    Or you could actually use something like the ?: operator to determine the correct string. (Update: @Greg gave the syntax for this. See that answer)