Hi,
I am stuck in the following code.I'm beginner in C++. I am facing problem in the following code.if any one from you help me it will be very helpful to me.
#include<iostream>
using namespace std;
class vector
{
int *v;
int size;
public:
vector(int m)
{
cout<<"In the constructor of vector which takes argument of int"<<endl;
v=new int[size=m];
cout<<"Declared array of size and pointed to pointer v"<<endl;
for(int i=0;i<size;i++)
{
}
*/
}
int operator *(vector &y)
{
cout<<"In operator function"<<endl;
int sum=0;
for(int i=0;i<size;i++)
{
sum +=this->v[i] * y.v[i];
}
return sum;
}
};
int main()
{
int x[]={5,6,7};
int y[]={7,8,9};
vector v1(3);
vector v2(3);
v1=x;
v2=y;
int r=v1*v2;
cout<<"Calling the * operator function"<<endl;
cout<<"The value of r:"<<r<<endl;
return 0;
}
Problem is in size variable.I'm assigning value size to 3 in first constructor but at when it calls second constructor which takes array pointer as argument value of size is changed despite calling from same object. Kindly help.Need help.
I do not see where the second constructor is called. Your code shall not be compiled because class vector has no an assignment operator that has a parameter of type int *.
Ah, I am sorry. As there is the conversion constructor then in the right side of the expression
v1 = x;
constructor vector( int * ) is called. As it initializes neither v nor size then vector v1 gets these undefined values due to the default copy assignment operator.
Thank you to "vlad". This program is in my text book.I was worried because i have never seen where text book is wrong. Problem is solved by removing the first constructor.
I assigned
v
in this constructor which was previously assigned in first constructor .
1 2 3 4 5 6 7
vector (T* a)
{
v=new T[size];for(int i=0;i<size;i++)
v[i]=a[i];
}