Delegation and MetaClass in C++

cobject-oriented

We have an OOP course at our university, while discussing the concepts I came across MetaClass and Delegation. As far as I know, these don't exist in C++.

Could someone give an example by which I can better understand how to simulate them instead.

Best Answer

Delegation can be achieved in C++ by using functors (made even more simple to declare in C++11 with lambdas). Any type can define a call operator member function, so you could say that C++ does have Delegation, just not in an easy syntax, but fixed with lambdas.

To be more precise (see comments), lambda don't act as delegate, functors - that are simply objects you can call like function and therefore move around until you need to call them - act as delegates. Lambdas expressions are just syntactic sugar allowing to define "in place" a functor directly in the code that will use it. Look in the wikipedia page for lambda for an introduction, it's the same as in C# or Python but a bit more powerful because you can put more than one-liners in.

MetaClass is harder but not impossible : look for reflection libraries for similar features. However, it's very rare that such features are really useful in C++ as you can read there the reasons. Most of the time, RTTI is enough.