Is this method of adding things to members of a class a legitimately used thing in an actual job scenario? When im looking at it, it doesn't seem syntactically right and pretty damn unneeded. Im just trying to figure out if this is something i'd ever actually use outside of school classes.
Some of C++s power stems from the possibility to overload operators. As always with great power comes great responsibility. Operators can be overloaded to do the obvious, for example nobody would be surprised by code like this
Matrix a{ {1,2},{2,3} };
Matrix c = a + a;
Maybe you don't even notice that +
here is a custom operator. C++ by itself cannot add two matrices. One downside of operator overloading is that you can overload them to do basically anything and sometimes it isnt that obvious. The line between a good operator overload and one that leads to confusing code is thin.
Concerning your concrete example, it is a pattern that you can also find elsewhere. Eigen is a well known algebra library. An example from their documentation is:
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
Matrix2d a;
a << 1, 2,
3, 4;
MatrixXd b(2,2);
b << 2, 3,
1, 4;
std::cout << "a + b =\n" << a + b << std::endl;
std::cout << "a - b =\n" << a - b << std::endl;
std::cout << "Doing a += b;" << std::endl;
a += b;
std::cout << "Now a =\n" << a << std::endl;
Vector3d v(1,2,3);
Vector3d w(1,0,0);
std::cout << "-v + w - v =\n" << -v + w - v << std::endl;
}
Note the use of the <<
operator to set the matrix elements. They add some comma operator voodoo, but the use of the <<
operator is rather similar to what you are supposed to implement.
Is this method of adding things to members of a class a legitimately used thing in an actual job scenario?
Yes. Using the operator<<
to "insert" elements into an object is perfectly legitimate. You will see such uses of operator overloading in various libraries. If an operator is used in such a way of course it requires proper documentation, because knowing the C++ language is not sufficient to know what an operator actually means in a certain context.