user2991252
user2991252

Reputation: 788

Overloading operator= does not work

I want to overload the operator = and I have the following operator-function

int IntegerClass::operator=(IntegerClass integer) {
  return  integer.number;
}

This should be correct?

In another class I want to assign the objects private member (int) to another int i.e.

int x = integerClass; 

but when I compile I get the following error

error: cannot convert 'std::IntegerClass' to 'int' in initialization

What is wrong with my implementation of operator-overloading and how should the function look like?

Upvotes: 0

Views: 421

Answers (1)

Antimony
Antimony

Reputation: 39511

Your operator overloads assignment of one IntegerClass to another, but you're trying to assign (actually it's initialization) to a built in int. You need to define an implicit conversion operator.

The code should be something like this (sorry I don't remember the exact syntax)

IntegerClass::operator int() {
  return number;
}

Upvotes: 4

Related Questions