0

I have two C++-classes A and B that I can't change for various reasons. However, I'd like to be able to define a multiplication a*a and a*a. (Think of A as a rotation matrix and b as a vector). I of course could define a mult(const A& a, const B& b) but that gets unreadable if I have expressions like a*a'*b.

Is there a way to overload the *-operator for these classes without changing their code?

(If this is not possible, was there ever a discussion to add this feature to the language?)

FooTheBar
  • 774
  • 1
  • 8
  • 19

2 Answers2

2

You can define a global operator*() function exactly like you would do mult():

const B& operator*(const A& a, const B& b) {
    // code goes here
}
Code-Apprentice
  • 76,639
  • 19
  • 130
  • 241
2

If you cannot change the classes at all you can still write a global operator* like

B operator*(const A& a, const B& b)

But you will not be able to modify any of the private members of the classes unless the classes provide accessers to them

NathanOliver
  • 161,918
  • 27
  • 262
  • 366