manabreak
manabreak

Reputation: 5597

Are pointer types the only way to "prevent" constructor being called in declaration?

I've tried to search for this, but I haven't found any answers. Let's look at this:

class Foo
{
    Foo();
    Bar a; // 'a', the object, gets created (even if I don't want to!)
    Bar* b; // 'b', the pointer, gets created, but the object doesn't
}

Foo::Foo()
{
    a = a(); // I'd like to create 'a' here instead. This just "replaces" it
    b = new Bar(); // 'b', the object, gets created
}

My question is: can I declare an object without creating it as well? Or do I always have to use pointers?

Upvotes: 0

Views: 46

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

My question is: can I declare an object without creating it as well?

No.

Or do I always have to use pointers?

No. Pointers are one option. There are others, such as boost::optional (std::optional is also in the process of standardization). There are also smart pointers (std::unique_ptr or std::shared_ptr). A standardly available, pre-c++11 option which is easier to manage than a raw pointer would be a std::vector where you only ever add one element.

But are you absolutely sure you need this?

Upvotes: 5

Related Questions