Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 256
Quantum7 Avatar asked Apr 29 '09 00:04

Quantum7


People also ask

Can you declare a variable without initializing?

If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values.

What is the difference between declaring and initializing?

Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.

How do you initialize an object?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).


1 Answers

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

Animal a(happyDay() ? "puppies" : "toads"); 
like image 56
Greg Hewgill Avatar answered Oct 01 '22 11:10

Greg Hewgill