Question

Is there any possible way to overload operator* in such way that it's assigning and observing functions are defined apart?

class my_class
{
  private:
    int value;
  public:
    int& operator*(){return value;}
};

int main()
{
  my_class obj;
  int val = 56;

  *obj = val;   // assign
  val  = *obj;  // observe, same operator* is called
}
Was it helpful?

Solution

Sort of -- you can have the operator* return an instance of another class, rather than returning a reference directly. The instance of the other class then defines both a conversion operator and an assignment operator.

(In your sample code, it looks like you've overloaded the multiplication operator when you meant to overload the dereferencing operator; I'll use the dereferencing operator below.)

For example:

class my_class
{
   friend class my_class_ref;

public:
   my_class_ref operator*() { return my_class_ref(this); }

private:
   int value;
};

class my_class_ref
{
public:
   operator int() { return owner->value; } // "observe"
   my_class_ref& operator=(int new_value) { owner->value = new_value; return *this; } // "assign"

private:
   my_class* owner;

   my_class_ref(my_class* owner) { this->owner = owner; }
};

There are some caveats. For example, as my_class_ref is implemented with a pointer to its parent class, your code must be careful that my_class_ref always has a lifetime shorter than the lifetime of the corresponding my_class -- otherwise you will dereference an invalid pointer.

In practice, if you pretend that my_class_ref doesn't exist (i.e. never declare a variable with that class) it can work very well.

OTHER TIPS

Write your class like so

class my_class
{
  private:
    int value;
  public:
    int operator*() const { // observing
        return value;
    }
    int& operator*() { // assigning
        return value;
    }
};

Then these operators are dissambiguated by constness, so code like this is possible

int _tmain(int argc, _TCHAR* argv[])
{
    my_class a;
    *a = 1; // assigning 
    int k = *(const_cast<my_class const&>(a)); // observing
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top