operator overloading

#include<iostream>

class Complex
{

public :
Complex (double real=0, double imag=0): _real(real) , _imag(imag){}
double getReal()const {return _real;}
private:
double _real,_imag;
};
template<class T,int d>
class Container
{
public :
Container():_arr(new T[d]){}
Container(Container<T,d+2>&other): _arr(new T[d]){}
T getItemAtIndex(int index) const {return _arr[index];}
Container<T, d - 2> setItemAtIndex(T item , int index) { _arr[index]= item; return *this; }
private : T* _arr;
};
int main()
{
Container <Complex,7> container;
Container <Complex,5> container2;
container2 = container.setItemAtIndex(*new Complex(1,2),0);
std::cout<<container2.getItemAtIndex(0).getReal();
system("pause");
}
container2 = container.setItemAtIndex(*new Complex(1,2),0);
I didnt overload the operator = for class of type container so why the compiler didn't tell me there is a problem here and it don't know what = means for container2=container;
it also didnt affect the values of container2 i know i should overload = and tell the compiler what to do
You get a default assignment operator if you don't define one. The default operator just copies the values of the variables. So you simply got another container that points to the same elements as the first container. If you print it out it will seem to have worked. But if you change something in container2 the change will also be seen in container. That's a problem! You need to define an assignment operator that makes it's own copy of the dynamic array.
Last edited on
yeah but even with the change in container container2 was not affected so in place it should print 1 it printed 0
if container2 got a pointer to container it should had print 1 but for some reasons it still print the original values with no changes
Topic archived. No new replies allowed.