Search code examples
c++operator-overloadingoperatorsoverloadingassignment-operator

How do I overload the assignment operator as to allow my class to equal a primitive type such as 'int'


So I am trying to do a program that is simply overloading many operators, but for some reason whenever I try to overload the assignment operator, I get an error that says

error: conversion from 'int' to non-scalar type 'Foo' requested

    class Foo {
        int value;
    public:
        operator int() const;
        Foo& operator=(const int &val) { value = val; return this; }
        ...
    };
    int main()
    {
        Foo a = 8, b = 9;
        ...
        return 0;
    }

I have also tried it without the operator= statement and without the operator int() const; statement, but I just can't seem to get it to compile.


Solution

  • You've confused assignment with initialization.

    Foo f = 1; //initialization
    f = 2; //assignment
    

    You need to make a constructor that accepts an int too.

    Foo(int i) : value(i) {}
    
    //main
    
    Foo f = 1; //uses constructor
    

    Being that it is a single argument constructor (converting constructor), if you don't wish int to be implicitly convertible to Foo, you should make the constructor explicit.