views:

189

answers:

3

When you create a new object in C++ that lives on the stack, (the way I've mostly seen it) you do this:

CDPlayer player;

When you create an object on the heap you call new:

CDPlayer* player = new CDPlayer();

But when you do this:

CDPlayer player=CDPlayer();

it creates a stack based object, but whats the difference between that and the top example?

+10  A: 

The difference is important with PODs (basically, all built-in types like int, bool, double etc. plus C-like structs and unions built only from other PODs), for which there is a difference between default initialization and value initialization. For PODs, a simple

T obj;

will leave obj uninitialized, while T() default-initializes the object. So

T obj = T();

is a good way to ensure that an object is properly initialized.

This is especially helpful in template code, where T might either a POD or a non-POD type. When you know that T is not a POD type, T obj; suffices.

sbi
User-defined types can also be PODs, in which case they will behave like built-ins when no explicit initialization is done.
Konrad Rudolph
@Konrad: You're right, the distinction is between PODs and non-PODs! Thank you for pointing this out, I changed my answer accordingly.
sbi
In C++0x, you can ensure proper initialization with `T obj{};`.
FredOverflow
There some other differences... `T obj = T()` requires that the copy constructor is available (even if the compiler will elide the copy).
David Rodríguez - dribeas
@FredOverflow: Doesn't this declare a function?
sbi
@David: Yes, that's right. However, I'm not sure it's relevant enough for the question to add it to my answer.
sbi
@sbi: Note the curly braces.
FredOverflow
@FredOverflow: Oh my.
sbi
+4  A: 

When you create a new object in C++ that lives on the stack, (…) you do this:

CDPlayer player;

Not necessarily on the stack: variables declared in this way have automatic storage. Where they actually go depends. It may be on the stack (in particular when the declaration is inside a method) but it may also be somewhere else.

Consider the case where the declaration is inside a class:

class foo {
    int x;
};

Now the storage of x is where ever the class instance is stored. If it’s stored on the heap, then so is x:

foo* pf = new foo(); // pf.x lives on the heap.
foo f; // f.x lives where f lives, which has (once again) automatic storage.
Konrad Rudolph
@Tony: Does this really answer the question? It was rather meant as a supplementary comment …. It doesn’t touch the difference between your first and third code at all, since other answers have already done that.
Konrad Rudolph
A: 
CDPlayer* player = new CDPlayer();

What this actually does is create a pointer on the stack and makes it point to a CDPlayer object allocated on the heap.

Ferruccio