Given a user defined class with a default constructor (let's call the
class C), is there any semantic difference between
C* c = new C;
and
C* c = new C();
? I am thinking they are equivalent, as demonstrated by the program
listing below. If not, which style is more commonly preferred?
I know with primitive types, e.g. int, there is a difference.
#include <iostream>
class C {
public:
C() { std::cout << "C()\n"; }
};
int main()
{
C* a = new C;
C* b = new C();
delete a;
delete b;
int* c = new int;
int* d = new int();
std::cout << *c << '\n' << *d << '\n';
delete c;
delete d;
return 0;
}
Output I get is:
C()
C()
3277336
0
--
Marcus Kwok
class C), is there any semantic difference between
C* c = new C;
and
C* c = new C();
? I am thinking they are equivalent, as demonstrated by the program
listing below. If not, which style is more commonly preferred?
I know with primitive types, e.g. int, there is a difference.
#include <iostream>
class C {
public:
C() { std::cout << "C()\n"; }
};
int main()
{
C* a = new C;
C* b = new C();
delete a;
delete b;
int* c = new int;
int* d = new int();
std::cout << *c << '\n' << *d << '\n';
delete c;
delete d;
return 0;
}
Output I get is:
C()
C()
3277336
0
--
Marcus Kwok
Comment