Goldman Sachs Interview Question
Developer Program EngineersThere are multiple ways.
1. Use vector STL.
class A
{
int p;
public:
A(int i)
{
p=i;
cout<<"Called"<<endl;
}
A(const A & rhs) :p(rhs.p) {
cout << "Copied\n";
}
};
int main()
{
vector<A> v(5,A(1));<-------5 objects are constructed.
return 0;
}
output here: ideone.com/lHX5W
2. Call constructor for each object.
A arr[3]={A(1),A(2),A(3)};
This would be better if we want to initialize different objects with different values.
The first object is initialized with1, second with 2 & so on.
However,in the first method using vector, only one object is constructed & initialized with 1 [in our case], & copy constructor is called 5 times to copy that object.
If you call new, then there will be a constructor call which will search for the default constructor. And, since there is no default constructor and the compiler can't create it because of presence of a parametrized constructor, it will report error.
So, the best you is to allocate the memory C-style and then initialize it.
class A{
public:
int a;
A(int b): a(b){}
};
int main()
{
A *a1,a2(1);
a1 = (A*)malloc(sizeof(A)*10); // equivalent to A[10].
for(int i=0;i<10;i++) a1[i]=a2; // Initialization is important in any program.
for(int i=0;i<10;i++) cout<<a1[i].a;
return 0;
}
A a[10] = new A[10];
for( int i=0; i<10; i++)
{
a[i] = new A( i ); // initialized to i;
}
#include<new>
using namespace std;
class A{
public:
A(int i)
{
k=i;
}
~A(){};
void fun();
private:
int k;
};
class B{};
int main()
{
void *ptr= operator new[](10*sizeof(A));
A *p=static_cast<A*>(ptr);
for (int i=0; i<10; ++i)
{
new(&p[i]) A(i);
}
for(int i=9; i>=0; --i)
{
p[i].~A();
}
operator delete [] (p);
return 0;
}
//Java solution
private A[ ] a;
public A(int i) {
if( a == null) {
System.out.println("executing first time" + i);
a = new A[i];
}
if(i <= 0) {
// done with initialization
} else {
System.out.println("creating object A ..." + i);
a[--i] = new A(i); // creates 'i' number of 'A' objects
}
}
//Java solution
private A[ ] a;
public A(int i) {
if( a == null) {
System.out.println("executing first time" + i);
a = new A[i];
}
if(i <= 0) {
// done with initialization
} else {
System.out.println("creating object A ..." + i);
a[--i] = new A(i); // creates 'i' number of 'A' objects
}
}
//Java solution
private A[ ] a;
public A(int i) {
if( a == null) {
System.out.println("executing first time" + i);
a = new A[i];
}
if(i <= 0) {
// done with initialization
} else {
System.out.println("creating object A ..." + i);
a[--i] = new A(i); // creates 'i' number of 'A' objects
}
}
//Java solution
private A[ ] a;
public A(int i) {
if( a == null) {
System.out.println("executing first time" + i);
a = new A[i];
}
if(i <= 0) {
// done with initialization
} else {
System.out.println("creating object A ..." + i);
a[--i] = new A(i); // creates 'i' number of 'A' objects
}
}
Sample s[5] = {1,2,3,4,5};
- Nageswar May 14, 2011