Re: Allocating memory for an object twice
prasoonthegreat@gmail.com wrote:
#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;
It's easier just to do
v=new T[size]();
(note the parentheses), and the array will be zero-initialised.
cout<<"Hello 1";
}
vector(T *a)
{
//v=new T[size];
for(int i=0;i<size;i++)
v[i]=a[i];
What if the pointer points to an array that is smaller than 'size'? You
would get *undefined behaviour*!
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;
}
};
[..]
why m i getting seg fault
Read about "The Rule of Three".
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask