tags:

views:

131

answers:

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

+1  A: 

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
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
This question is answered here:Do the parentheses after the type name make a difference with new?Thank you
q0987