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

279 Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

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;
};
0
On

You need to provide conversion operator:

class A{
...
    operator int32_t() const 
    { 
       return this->data;
    }
};

Any conversion operator is implemented as:

operator DATATYPE()
{
    return ...;
}

The return type of such conversion operator is DATATYPE itself (hence int32_t in code given above). Since this conversion operator doesn't (shouldn't) change the content of this instance, it should be declared const.