why there is run time error - stack overflow
Jun 15, 2013 at 3:50pm
Hi all,
i went over some code and i was trying to figure out why it cause run time error of stack overflow.
attached the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class opOverload{
public:
bool operator==(opOverload temp);
};
bool opOverload::operator==(opOverload temp){
if(*this == temp ){
cout<<"The both are same objects\n";
return true;
}
else{
cout<<"The both are different\n";
return false;
}
}
void main(){
opOverload a1, a2;
a1= =a2;
}
| |
i thought that when i execute the second line in main function, it calls to "==" function of opOverload class (overload function) and makes compare.
but when i ran it , it got into infinite loop until overflow.
WHY?
Thank you!
Jun 15, 2013 at 3:57pm
In this statement
if(*this == temp ){
you are recursively calling the operator. Each time when it is called it creates in stack local variable temp.
Jun 15, 2013 at 3:59pm
I'd like to appent that it would be more clear that this statement
if(*this == temp ){
is equivalent to
if ( ( *this ).operator ==( temp ) ){
Jun 15, 2013 at 4:01pm
By the way main shall be declared as
int main()
Topic archived. No new replies allowed.