Look at the following code....
In the above code....althoug h memory has been allocated to object v1 in the default constructor ......why do we need to allocate it again in the parametrized constructor???? ...otherwise i am getting a seg fault
Code:
#include<iostream>
using std::cout;
using std::endl;
const int size=3;
template<class T>
class vector
{
T *v;
public:
vector()
{
v=new T[size];
for(int i=0;i<size;i++)
v[i]=0;
cout<<"Hello 1";
}
vector(T *a)
{
//v=new T[size];
for(int i=0;i<size;i++)
v[i]=a[i];
cout<<"Hello";
}
/*void operator=(const T *a)
{
for(int i=0;i<size;i++)
v[i]=a[i];
}*/
T operator*(const vector &y)
{
T prod=0;
for(int i=0;i<size;i++)
prod += this->v[i] * y.v[i];
return prod;
}
};
int main()
{
int x[3]={1,2,3};
int y[3]={4,5,6};
float a[3]={1.7,2.3,3.2};
float b[3]={1.9,2.4,3.8};
vector <int> v1;
vector <int> v2;
vector <float> v3;
vector <float> v4;
v1=x;
v2=y;
v3=a;
v4=b;
int Prod_Int = v1 * v2;
float Prod_Float = v3 * v4;
cout<<"Prod_Int = "<<Prod_Int<<endl;
cout<<"Prod_Float = "<<Prod_Float<<endl;
return 0;
}
Comment