new operator detail?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Giorgos P.

    new operator detail?

    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.


  • Victor Bazarov

    #2
    Re: new operator detail?

    "Giorgos P." <gpouikli@ee.du th.gr> wrote...[color=blue]
    > classname *ptr = new classname();
    >
    > Any idea why the parenthesis in the end?I thought that " new " worked just
    > fine with the classname alone?[/color]

    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


    Comment

    • Adam Fineman

      #3
      Re: new operator detail?

      Giorgos P. wrote:[color=blue]
      > classname *ptr = new classname();
      >
      > Any idea why the parenthesis in the end?I thought that " new " worked just
      > fine with the classname alone?[/color]

      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

      Comment

      • Adam Fineman

        #4
        Re: new operator detail?

        Victor Bazarov wrote:[color=blue]
        > <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.
        >[/color]
        Ah, right.

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

        - Adam

        Comment

        • Andrey Tarasevich

          #5
          Re: new operator detail?

          Giorgos P. wrote:[color=blue]
          > classname *ptr = new classname();
          >
          > Any idea why the parenthesis in the end?I thought that " new " worked just
          > fine with the classname alone?
          > ...[/color]

          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.

          --
          Best regards,
          Andrey Tarasevich
          Brainbench C and C++ Programming MVP

          Comment

          Working...