Well i am new to c++ programming, i was trying to play with copy constructor and overloaded operator. They both worked fine individually but are creating problem when used in single program. I am not able to figure out the problem, where am i going wrong?? Please Help me.
Thanks in advance.
class Test
{
public:
Test()
{
length=0;
}
Test(int x)
{
length=x;
}
Test(Test &x)
{
cout<<"copy constructor\n";
length=x.length;
}
int getdata()
{
return length;
}
Test operator ++(int)
{
return Test(length++);
}
Test operator +(Test x)
{
Test y;
y.length=length+x.length;
return y;
}
private:
int length;
};
int main(int argc,char *argv[],char *envp[])
{
Test obj;
cout<<"obj="<<obj.getdata()<<endl;
Test obj2=obj++;
cout<<"obj2="<<obj2.getdata()<<endl;
cout<<"obj="<<obj.getdata()<<endl;
obj2++;
obj=obj+obj2;
cout<<"obj="<<obj.getdata()<<endl;
return 0;
}
What is the problem? Compiler eroors or what? The only thing I noted from a glance is that in your overloaded operators you should use the this pointer to more explicitly say what instance your referring too.
EDIT:
I realize that your ++ operator is messed up. Where you say obj2++, you're not actually incrementing the length of obj2. Remember, the function just returns a instance of the class with a length of one higher than its parameter, and doesn't actually change the value of anything.
i am getting error : no matching function for call to 'Test::Test(Test)' in line
Test(Test &x) //copy constructor
{}
and
Test obj2=obj++;
and as you said for the use of this pointer, i feel there is no use for this pointer as there are no ambiguity (or clashes) for length variable, where ever it is used.