Search code examples
c++operator-overloadingassignment-operator

C++ override operator= to call ToInt() method


Hi i'm trying to overload the assignment operator of a class to return an class Member (data).

class A{
 public:
  int32_t ToInt32() { return this->data; }
  void SetData(int32_t data) { this->data=data; }
 private:
  int32_t data;
}

I want to overload the = operator, so that i can do the following:

A *a = new A();
a->SetData(10);
int32_t Testint;
Testint = a;

and now a should be 10.

How can i do that?


Solution

  • You can’t do that since a is a pointer. You can only overload operators for custom types (and pointers are not custom types).

    But using a pointer here is nonsense anyway. You can make the following work:

    A a = A{};
    a.SetData(10);
    int32_t Testint;
    Testint = a;
    

    In order to do this, you overload the implicit-conversion-to-int32_t operator, not operator=:

    public:
        operator int32_t() const { return data; }
    

    A word on code style: having setters is usually a very bad idea – initialise your class in the constructor. And don’t declare variables without initialising them. So your code should actually look like this:

    A a = A{10};
    int32_t Testint = a;
    

    … two lines instead of four. The definition of A becomes simpler as well:

    class A {
    public:
        A(int32_t data) : data{data} {}
    
        operator int32_t() const { return data; }
    
    private:
        int32_t data;
    };