0

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?

user2991252
  • 760
  • 2
  • 11
  • 28
  • 1
    `int x = integerClass` doesn't invoke any operators (it is initialization and not assignment), and especially not `IntegerClass::operator=`. If any, you could try implementing `IntegerClass::operator int()` instead to support implicit conversion to `int`. –  Dec 21 '13 at 16:34
  • 2
    What is this `std::IntegerClass`? The standard library doesn't have such a class AFAIK. You added your class to `std`? That's bad. – leemes Dec 21 '13 at 16:39
  • 1
    [a very good read](http://stackoverflow.com/questions/4421706/operator-overloading) – Koushik Shetty Dec 21 '13 at 16:43
  • @leemes .. It may be due to that Eclipse autogenerates a namespace that embraces the whole class .i.e namespace std { class IntegerClass {} } ? – user2991252 Dec 21 '13 at 17:11
  • Eclipse is your IDE; if that was true you'd see the code. – leemes Dec 21 '13 at 18:41

1 Answers1

4

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;
}
Antimony
  • 37,781
  • 10
  • 100
  • 107
  • 2
    To expand on this a bit: `int x = integerClass;` is not an assignment statement. If you did `int x; x = integerClass;` then it would be an assignment. – Kristopher Johnson Dec 21 '13 at 16:36
  • 1
    Probably worth mentioning that introducing classes in the `std` namespace is a very bad idea (and is possibly undefined behavior IIRC), except for the cases where it is allowed. – Shoe Dec 21 '13 at 16:48
  • Thanks it works!!! But i do not understand why no return type has to be specified. If it returns an integer (number) the declaration should look like this int IntegerClass::operator int() .. shouldnt it? – user2991252 Dec 21 '13 at 16:50
  • 1
    @user2991252, the whole purpose of `operator int` is to return an int. `int operator int` is redundant. – Shoe Dec 21 '13 at 16:53