new operator detail?

G

Giorgos P.

classname *ptr = new classname();

Any idea why the parenthesis in the end?I thought that " new " worked just
fine with the classname alone?
Thanks in advance.
 
V

Victor Bazarov

Giorgos P. said:
classname *ptr = new classname();

Any idea why the parenthesis in the end?I thought that " new " worked just
fine with the classname alone?

If 'classname' is a POD (plain old data), the difference is
that without parentheses the object is left uninitialised,
and with parentheses it is default-initialised. For non-POD
types it doesn't matter.

Victor
 
A

Adam Fineman

Giorgos said:
classname *ptr = new classname();

Any idea why the parenthesis in the end?I thought that " new " worked just
fine with the classname alone?

I believe that if you use the classname without parenthesis, it just
calls the default, no-argument constructor. In other words, they are
equivalent.

The parentheses syntax is required if you have a constructor that takes
arguments.

- Adam
 
A

Andrey Tarasevich

Giorgos said:
classname *ptr = new classname();

Any idea why the parenthesis in the end?I thought that " new " worked just
fine with the classname alone?
...

It depends on the type designated by 'classname'. Unfortunately, you
didn't provide any details about this type.

If 'classname' names a non-POD class type, the '()' makes no difference
whatsoever, i.e. 'new classname' and 'new classname()' do the same thing.

For POD types the '()' is essential - it causes the object to be
default-initialized, while 'new classname' will not initialize it at all.
 
A

Adam Fineman

Victor said:
<snip>
If 'classname' is a POD (plain old data), the difference is
that without parentheses the object is left uninitialised,
and with parentheses it is default-initialised. For non-POD
types it doesn't matter.
Ah, right.

Ignore my other post in this thread. I was wrong.

- Adam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,138
Messages
2,570,801
Members
47,348
Latest member
nethues

Latest Threads

Top