0

Hey i want to implement delegate in c++ i know how to do in c# i posting my code but don't know how i convert this to c++

public class Events {
    public delegate void Action();
    public Action OnPrintTheText = delegate{};
}

public class ABC {
    private Event evt;
    public ABC() {
        evt  = new Event();
    }
    public void printText() {
        evt.OnPrintTheText();
    }
    public Event getEventHandler() {
        return evt;
    }
}
public class Drived {
    private ABC abc;

    public Drived() {
        abc = new ABC();
        abc.getEventHandle().OnPrintTheText += OnPrint;
    }
    ~Drived() {
        abc.getEventHandle().OnPrintTheText -= OnPrint;
    }
    public void OnPrint() {
        Debug.Log("ABC");
    }
}

now whenever i call printText it will automatically call the OnPrint() of Drived class so is there anyway to implement this to c++?

MAV
  • 7,260
  • 4
  • 30
  • 47
Ravi
  • 95
  • 1
  • 3
  • 10
  • 1
    Have a look at pure virtual functions and abstract classes. A delegate is nothing more than a degenerate source/sink interface declaration with either just one particular function. Function pointers are also similar. – πάντα ῥεῖ Mar 02 '14 at 19:09
  • Do you mean you want to implement that in C++/CLI? – Daniel A. White Mar 02 '14 at 22:26
  • 1
    This is an amazing article on C++ delegates: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible – Avi Tevet Mar 03 '14 at 05:18

2 Answers2

1

C# does a lot of management behind the scenes. Broadly, a delegate in C# is a container of function references.

In C++, you can create a similar delegate by using a functor template that wraps an object instance and a member function for class member functions, and also one that just wraps a function (for non members). Then you can use a standard container to maintain the list/array/map/etc of the instances of the functors, and this will provide you with the functionality of the C# delegate and also allow adding and removing 'actions' (C#: += and -=).

Please see my answer here on how you can create such a templated functor for class members. The non-member case is simpler since it does not wrap an object instance.

Community
  • 1
  • 1
DNT
  • 2,356
  • 14
  • 16
0

Take a look at function pointers: http://www.newty.de/fpt/index.html

A function pointer is a pointer that points to a specific function, basically what a delegate is.

Look at this: What is the difference between delegate in c# and function pointer in c++?

Community
  • 1
  • 1
Bauss
  • 2,767
  • 24
  • 28