Stuck in this need help

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++)
{

v[i]=0;
cout<<"Assigned v["<<i<<"]=0"<<endl;
}
}
vector(int *a)
{
cout<<&size<<endl;
cout<<"Size:"<<size<<endl;
/* for(int i=0;i<size;i++)
{
//v[i]=a[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 *.
Last edited on
yes, the second constructor is called here:
1
2
v1=x;
v2=y;

A constructor is only called for a newly created object. After the assignment of v1/v2 they are not the object created above.

Test it with cout << this
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.

Last edited on
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];
}


and now in my main function

Instead of declaring this
1
2
vector <int> v1;
vector <int>v2;


i declared in following manner.
1
2
vector <int> v1=x;
vector <int>v2=y;

And yes Size is constant here which is
3
Topic archived. No new replies allowed.