92

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?

3
  • 1
    see RAII (resource acquisition is initialization)
    – newacct
    Commented Apr 29, 2009 at 0:57
  • 2
    if it is a non-static global/namespace-scope, then it's worth to note you can actually declare without initializing it: extern Animal a; ... Animal a(stuff); Commented Apr 29, 2009 at 14:25
  • @newacct: A link would help stackoverflow.com/questions/2321511/…
    – spinkus
    Commented Jun 10, 2014 at 22:08

10 Answers 10

60

You can't use references here, since as soon as you'd get out of the scope, the reference would point to a object that would be deleted.

Really, you have two choices here:

1- Go with pointers:

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

// ...
delete a;

or with a smart pointer

#include <memory>

std::unique_ptr<Animal> a;
if( happyDay() ) 
    a = std::make_unique<Animal>( "puppies" );
else
    a = std::make_unique<Animal>( "toads" );

2- Add an Init method to Animal:

class Animal 
{
public:
    Animal(){}
    void Init( const std::string& type )
    {
        m_type = type;
    }
private:
    std:string m_type;
};

Animal a;
if( happyDay() ) 
    a.Init( "puppies" );
else
    a.Init( "toads" );

I'd personally go with option 2.

1
  • 4
    If you go with option 1, you should use a unique_ptr.
    – Chronial
    Commented Jun 7, 2020 at 15:07
50

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

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

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)

3
  • 3
    +1. This is the general form of the solution -- wrap it inside a function. (As you say, ?: often does the job and is more convenient when it does, but writing a separate function will always work.) Commented Apr 29, 2009 at 3:55
  • However, if your constructor needs to take multiple arguments, do you make multiple functions, one for each argument?
    – newacct
    Commented Apr 29, 2009 at 6:22
  • 1
    There are some studies that show that it is better to not have constructors with multiple arguments but rather to create with default and then use setters. That being said, yes, you'd do a function per argument, or even better, have an interim struct to represent the cohesive elements that constitute the parameters, if they are related.
    – Uri
    Commented Apr 29, 2009 at 7:09
18

I prefer Greg's answer, but you could also do this:

char *AnimalType;
if( happyDay() ) 
    AnimalType = "puppies";
else
    AnimalType = "toads";
Animal a(AnimalType);

I suggest this because I've worked places where the conditional operator was forbidden. (Sigh!) Also, this can be expanded beyond two alternatives very easily.

10

Since c++17, there is now an overhead-free way to do this: std::optional. The code in this case would be:

#include <optional>

std::optional<Animal> a;
if (happyDay()) {
    a.emplace("puppies");
} else {
    a.emplace("toads");
}
4
  • 1
    This could be a good solution. It's not quite the intended use of optional (marking values that may or may not be initialized) but it does avoid calling a's default constructor.
    – Quantum7
    Commented Jun 9, 2020 at 8:20
  • Note that optional does have a tiny amount of overhead for storing the bool (8 bytes on my system) and initializing itself.
    – Quantum7
    Commented Jun 9, 2020 at 8:24
  • Gist exploring this (and other) solutions: gist.github.com/sbliven/359d180753febc4777ac79bb97685b5b
    – Quantum7
    Commented Jun 9, 2020 at 8:52
  • 1
    @Quantum7 a good compiler will completely optimize away the optional: godbolt.org/z/x9gncT
    – Chronial
    Commented Jun 28, 2020 at 20:20
8

If you want to avoid manually managing memory, you could use a smart pointer:

std::unique_ptr<Animal> p_a;
if ( happyDay() )
    p_a = std::make_unique<Animal>( "puppies" );
else
    p_a = std::make_unique<Animal>( "toads" );

// do stuff with p_a-> whatever.  When p_a goes out of scope, it's deleted.

If you still want to use the . syntax instead of ->, you can do this after the code above:

Animal& a = *p_a;

// do stuff with a. whatever
2
  • This needs to be changed to auto_ptr<Animal> p_a(new Animal); otherwise the auto_ptr just has a null pointer. Though I like the second idea as it doesn't copy it - but you do have to be mindful that the life is in that scope. Commented Sep 16, 2013 at 0:26
  • 3
    @NathanAdams, an auto_ptr initialized with null is fine here, it will be either "puppies" or "toads" later. Having an extra "new Animal" is redundant.
    – fxam
    Commented Sep 24, 2013 at 16:03
7

In addition to Greg Hewgill's answer, there are a few other options:

Lift out the main body of the code into a function:

void body(Animal & a) {
    ...
}

if( happyDay() ) {
  Animal a("puppies");
  body( a );
} else {
  Animal a("toad");
  body( a );
}

(Ab)Use placement new:

struct AnimalDtor {
   void *m_a;
   AnimalDtor(void *a) : m_a(a) {}
   ~AnimalDtor() { static_cast<Animal*>(m_a)->~Animal(); }
};

char animal_buf[sizeof(Animal)]; // still stack allocated

if( happyDay() )
  new (animal_buf) Animal("puppies");
else
  new (animal_buf) Animal("toad");

AnimalDtor dtor(animal_buf); // make sure the dtor still gets called

Animal & a(*static_cast<Animal*>(static_cast<void*>(animal_buf));
... // carry on
1
  • Do you know if there's a way to make the placement new version guarantee correct alignment (Pre c++11)?
    – enobayram
    Commented Dec 9, 2012 at 23:52
3

The best work around is to use pointer.

Animal a*;
if( happyDay() ) 
    a = new Animal( "puppies" ); //constructor call
else
    a = new Animal( "toads" );
1
  • 4
    When using new, the variable is stored in heap and should be deleted later Commented Mar 15, 2020 at 3:52
2

There is a way to do this without pointers/heap memory, this syntax is just a bit gibberish. Here is an example using std::string. I don't recommend doing this unless you really need the performance.

uint8_t object[sizeof(std::string)];

int main() {
    if(true)
        new(&object) std::string("Your arguments");
    else
        new(&object) std::string("Your other arguments");

    (*(std::string*)(&object)).append("");
    std::cout << (*(std::string*)(&object));
    return 0;
}

The annoying part about this is you have to cast object to a string every time you want to use it:

(*(std::string*)(&object))
-6

Yes, you can do do the following:

Animal a;
if( happyDay() )
    a = Animal( "puppies" );
else
    a = Animal( "toads" );

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:

Animal a;
if( happyDay() )
    a.init( "puppies" );
else
    a.init( "toads" );

This way would be more efficient.

7
  • 2
    Are you sure about this? I think this will invoke default constructor and then an assignment operator, so you'll lose the old a.
    – Uri
    Commented Apr 29, 2009 at 0:24
  • Yeah, I forgot about the initial constructor at first. That's why I usually test my code before posting it... didn't this time...
    – DeadHead
    Commented Apr 29, 2009 at 0:27
  • 3
    Yea, but that assumes that (1) Animal has an accessible default constructor (it may not make sense to have a default constructor in some classes), (2) Animal has an assignment operator (some classes can't be assigned by design), and (3) constructing and assigning Animal has the same effect as constructing it directly.
    – newacct
    Commented Apr 29, 2009 at 0:27
  • 3
    Using an init() method is probably a bad idea as that implies the object is not valid after the constructor is finished. Commented Apr 29, 2009 at 0:29
  • 1
    @DeadHead: Careful with your syntax. Your Animal a(); line is a function prototype, not a variable declaration. Animal a; is what you mean (default constructor is still invoked).
    – Drew Hall
    Commented Apr 29, 2009 at 1:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.