Bloomberg LP Interview Question
Software Engineer / DevelopersIf T is a user defined class/struct, there is no difference.
However,
int *o = new int; // *o has not been initialized
int *o = new int(); // *o has been default initialized, ie *o == 0
Tested, the output is the same
1 #include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 int *o = new int;
8 int *p = new int();
9 cout << *o << endl;
10 cout << *p << endl;
11 }
./a.out
0
0
~
really it is compiler dependent. check out of below code
A is -842150451 B is -842150451
x is 009294A0 y is 0092A038
int main_contr()
{
class a
{
int aaa;
public:
a()
{
}
int geta()
{
return aaa;
}
};
a* A = new a;
a* B = new a();
cout << "A is " << A->geta() << " B is " << B->geta();
int* x = new int;
int* y = new int();
cout << "\nx is " << x << " y is " << y;
return 0;
}
Hey I tested that code too.. result is different..
int *w=new int; prints garbage and the other one prints zero
both have the same functionality...in first case the constructor is called implicitly while in the second case constructor is explicitly called
If this is the case then below code should not compile:
class test
{
public:
explicit test() {
cout<<"constructor called"<<endl;
}
};
void main()
{
test *ptr1 = new test;
test *ptr2 = new test();
getchar();
}
If there is a default constructor then both are same, otherwise different.
- maX June 15, 2011According to the latest C++ 2003 standard,
new T calls default initializer and,
new T() calls value initializer.
No constructor :
new T:
It causes default initialization of non-POD(*1) types.
POD types remain uninitialized. That is, indeterminate value.
new T():
For non-POD types default initialization.
POD types are zero initialized.
If there is a constructor which doesn't list the variables, then the same thing happens, default initialization for non-POD and zero/random values for POD according to new()/new.
*1. POD is Plain Old Data. That is a C-like struct. Ctors/Dtors/Funcs. etc make it non-POD.