-2

I just can't seem to find a simple explanation or example of the keyword operator= in C++.

e.g

#include <iostream>
using namespace std;

class A {};

class B {
public:
  // conversion from A (constructor):
  B (const A& x) {}
  // conversion from A (assignment):
  B& operator= (const A& x) {return *this;}
  // conversion to A (type-cast operator)
  operator A() {return A();}
};

int main ()
{
  A foo;
  B bar = foo;    // calls constructor
  bar = foo;      // calls assignment
  foo = bar;      // calls type-cast operator
  return 0;
}

What is operator=? I see mentions of it in overloading operators, but the majority of the online sources do not explain the keyword operator they just use it in their examples.

Could any one care to explain it?

I would also like to know why does the keyword this have a * in front of it? What is the difference between this-> and *this?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Zibele
  • 15
  • 1
  • 5

1 Answers1

0

I see mentions of it in overloading operators, but the majority of the online sources do not explain the keyword "operator" they just use it in their examples.

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.

Source: MSDN website

sam
  • 2,033
  • 2
  • 10
  • 13