1

Context: My C++ experience is about 3/10, so bear with me.

I'm curious to know if it's possible to attach a read callback function to a C++ object member, so that when I assign:

var = object.member;

this calls a callback, which updates member before returning it. I can achieve the same end by

...
var = object.GetMemberVal();
...
int FooClass::GetMemberVal()
{
    // update member value
    return this->member;
}

But val = object.member; (no parens) is a bit cleaner and seems closer to the spirit of object-orientedness... I think.

I think member function as callback may be related, but I'm not totally following.

Whether this is a good idea or not may be up for debate, I'm just interested to know if it's possible.

Community
  • 1
  • 1
berad
  • 91
  • 1
  • 4
  • 2
    What about `object.member = var`? What should happen in this case? – Zeta Dec 04 '13 at 10:27
  • Whel , you can , but it's a hack and it's not practical, you can create a class that will overload the `=` operator and call a callback for the left member or the right member. You also need to know the `member` to which instance it belongs ... – Raxvan Dec 04 '13 at 10:29

3 Answers3

0

If I understand you correct, you might want to use std::bind for this:

auto myGetMemberVal = std::bind(&FooClass::GetMemberVal, object);

// ...

int value = myGetMemberVal();  // Actually calls object.GetMemberVal()

The std::bind function creates a callable object, which will call the function you tell it to.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Borland C++ Builder had something like this called a property but it isn't a standard C++ feature.

Using standard C++ you can create a template class that wraps the member and implements at least these functions:

  • operator T : for reading the value. T is the type of the member (e.g. int)
  • operator = : for writing the value

For simple built in types it's fairly simple.

If you want the member to be just an int and you only want direct access to it (no wrappers), then you can't do it.

egur
  • 7,830
  • 2
  • 27
  • 47
0

Does this help your cause:

#include <iostream>


typedef int (*func)(int,int);

int f1(int x,int y)
{
  return x+y;
}

class A{

  int _x;
  int _y;
  int _z;

  public:

  A(int num1,int num2):_y(num1),_z(num2){}

  void set ( int (*f)(int x,int y))
  {
    _x = (*f)(_y,_z);
  }

  int get ()
  {
    return _x;
  }

};

int main()
{
  A instance(11,1);
  instance.set(f1);
  std::cout<<instance.get()<<std::endl;
}
Nik
  • 1,294
  • 10
  • 16