1

Possible Duplicate:
Do the parentheses after the type name make a difference with new?

Hello all,

/* Sorry for my original post and I correct my question as follows */

Assume that ClassA is a well-defined C++ class and has a default constructor, etc. What is the difference between the following two cases:

ClassA* pClassA = new ClassA;    // case I
classA* pClassA = new ClassA();  // case II

It has been considered as a good practice to use case I if possible.

What is the reason for this?

Because in case I only default constructor of ClassA will be called, while in case II, a temporary instance of ClassA will be constructed.

Is that correct?

Thank you

Community
  • 1
  • 1
q0987
  • 34,938
  • 69
  • 242
  • 387
  • 1
    you can always test your own guessing by creating copy constructor and default constructor and placing breakpoint inside copy ctor. – Andrey Aug 04 '10 at 17:48
  • 1
    No, it is not correct. And this has been asked a zillion times before. –  Aug 04 '10 at 17:48
  • @Andrey Or just make the copy constructor private. –  Aug 04 '10 at 17:49
  • Hello all, Thank you for your quick response. I think I made the wrong question above and I had corrected my post. – q0987 Aug 04 '10 at 18:02

1 Answers1

1

For the case of a defined constructor as you specified, there is no difference. You can test it by running this program:

#include <iostream>

struct A {
    A() { std::cout << "A()" << std::endl; }
    A(const A&) { std::cout << "A(const A&)" << std::endl; }
    A& operator=(const A&) { std::cout << "operator=(const A&)" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};

int main() {
    A *p1 = new A;
    A *p2 = new A();
}
Evan Teran
  • 87,561
  • 32
  • 179
  • 238
  • Trace statements aren't particularly useful for figuring out when copy constructors are called. In this case, the results are okay, but only because the copy constructor is legitimately not supposed to be called. – Dennis Zickefoose Aug 04 '10 at 18:29
  • This question is answered here: Do the parentheses after the type name make a difference with new? Thank you – q0987 Aug 04 '10 at 20:43