oplaTech About Teaching Archive
Oplatek's external memory

Why to prefer public functions instead of methods in C++?

It is more usable, because it allows type conversion!
e.g:

MyMatrix b; // suppose it support conversion to Matrix
MyMatrix c; // suppose it support conversion to Matrix
Matrix a = b + c; // works only with first solution


First solution: Allows type conversion

Matrix operator+( const Matrix & a, const Matrix & b);


Second solution: Does not allow type conversion on first operand

class Matrix {
public:
Matrix operator+(const Matrix & b);
}


Implementation of operator + from first solution:

Matrix operator+( const Matrix & a, const Matrix & b) {
// It is OK += as a method,
// because there is no need of type conversion on left side
x += y ;
return x;
}