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?
If you want to avoid garbage collection - you could use a smart pointer.
If you still want to use the . syntax instead of ->, you can do this after the code above:
Yes, you can do do the following:
That will call the constructors properly.
EDIT: Forgot one thing... When declaring a, you'll have to call a constructor still, whether it be a constructor that does nothing, or still initializes the values to whatever. This method therefore creates two objects, one at initialization and the one inside the if statement.
A better way would be to create an init() function of the class, such as:
This way would be more efficient.