#include <iostream>
using namespace std;
/**
* Definition of class A that stores an integer
*/
class A {
public:
// value stored
int value;
/**
* default constructor
* initialization of value to -1
*/
A() {
value = -1;
}
/**
* constructor with value
* @param v value to store
*/
A(int v) {
value = v;
}
/**
* print class contents
*/
friend ostream& operator<<(ostream& out, A& obj) {
out << obj.value;
return out;
}
};
// ----------------------------------------------
// function that will produce an error
// we are trying to exchange values
// ----------------------------------------------
int function_1(const A& x, const A& y) {
// by default lets assume 'x' is the smallest value
// and 'y' the biggest
A& smallest = const_cast<A&>(x);
A& biggest = const_cast<A&>(y);
cout << "> in function:" << endl;
cout << "smallest = " << smallest << endl;
cout << "biggest = " << biggest << endl;
// if it is not the case then exchance 'x' and 'y'
if (smallest.value > biggest.value) {
// !!!!! problem here !!!!!
// it is equivalent to: x = y
smallest = const_cast<A&>(y);
biggest = const_cast<A&>(x);
cout << "> in function after exchange:" << endl;
cout << "smallest = " << smallest << endl;
cout << "biggest = " << biggest << endl;
}
return (biggest.value - smallest.value);
}
// ----------------------------------------------
// valid function
// we are trying to exchange values
// ----------------------------------------------
int function_2(const A& x, const A& y) {
// work on values not references
int smallest = x.value;
int biggest = y.value;
cout << "> in function:" << endl;
cout << "smallest = " << smallest << endl;
cout << "biggest = " << biggest << endl;
if (smallest > biggest) {
swap(smallest, biggest);
}
return (biggest - smallest);
}
// ----------------------------------------------
// main function
// ----------------------------------------------
int main() {
A a1(7), a2(5);
cout << "==== with function_1 ====" << endl;
cout << "initially :" << endl;
cout << "a1 = " << a1 << endl;
cout << "a2 = " << a2 << endl;
int r = function_1(a1, a2);
cout << "r = " << r << endl;
// !!! a1 is modified after call to function !!!
cout << "finally :" << endl;
cout << "a1 = " << a1 << " !!! should be 7" << endl;
cout << "a2 = " << a2 << endl;
cout << "==== with function_2 ====" << endl;
A b1(7), b2(5);
cout << "initially :" << endl;
cout << "b1 = " << b1 << endl;
cout << "b2 = " << b2 << endl;
r = function_2(b1, b2);
cout << "r = " << r << endl;
cout << "finally :" << endl;
cout << "b1 = " << b1 << endl;
cout << "b2 = " << b2 << endl;
return 0;
}