c++ - creating vector using templates in cpp -


this example text book. creating vector using templates. in main function copy predefined array vectors. finally, multiply 2 vectors. although program compiles nicely program fails execute. whats wrong code.

#include <iostream>  const int size = 3;  template<class t> class vector {     t* v; public:     vector()     {         v = new t[size];         (int = 0; < size; i++){             v[i] = 0;         }     }      vector(const t* a)     {         (int = 0; < size; i++){             v[i] = a[i];         }     }      t operator * (const vector& y)     {         t sum = 0;         (int = 0; < size; i++){             sum += this->v[i] * y.v[i];         }         return sum;     } };  int main() {     int x[3] = { 1, 2, 3 };     int y[3] = { 4, 5, 6 };     vector<int> v1;     vector<int> v2;     v1 = x;     v2 = y;     int r = v1 * v2;     std::cout << r;     return 0; } 

first of in constructor

   vector(t *a)   {       for(int i=0;i<size;i++){          v[i]= a[i];      }   } 

you did not allocate array pointed v. pointer v not initialized. constructor has undefined behaviour.

and potential problem did not define copy assignment operator.

in these statements

v1 = x; v2 = y; 

temporary objects of type vector created , after assignment deleted. new created objects have invalid pointer v.

you have define @ least copy constructor, copy assignment operator , destructor.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -