Emulating a C# reference counted reference to an Interface?


I am using Juce ReferenceCountedObject and ReferenceCountedObjectPtr to provide memory management in my project.

This works great - particularly with the JUCE 2.0 changes. But theres one problem i’d really like to crack.

It is common practice to implement ( roughly ) what is in other languages called “interfaces” by means of an abstract virtual class.

[ Before I continue I shall make a small point - and that is that nearly 100% of my JUCE project only uses and needs SINGLE INHERITANCE i.e. only inherits from a SINGLE ReferenceCountedObject class- since the original code comes from a different language that does this. But although only inheriting from
on or no ancestor class my code can IMPLEMENT - i.e. inherit - from one or more INTERFACE ( abstract virtual _ classes ]

One can then define a variable, return value or class member to be an interface type - say IFoo and pas this around.

Only trouble is - this does not allow whatever os assigned to be reference counted.

Now I COULD specify all my interface abstract virtual classes to ALSO inherit from ReferenceCountedObject, but then I get the “diamond problem” since all my classes already inherit from this and now any that also
IMPLEMENT one or more interface will inherit TWICE.

So Jules and others - is there a way round this ? any chance of adding extra classes to achieve this to JUCE ?

The language I “hail from” - RealBasic - allows any class to inherit from a single ancestor, but can IMPLEMENT none, one or more interfaces.
Then in RB one can define a property or reference variable that is just - say IFoo and any object reference that implements IFoo can be assigned to this reference variable and when this reference goes out of scope the object gets managed like any and ultimately deleted as any other object reference .

So RB gets around this somehow via its ( hidden ) framework and its parser/compiler.

Any Ideas of how i can achieve the same thing in JUCE ?


Well, you don’t actually have to derive your class from ReferenceCountedObject in order to use a ReferenceCountedObjectPtr on it - any class that has a suitable set of incReference(), decReference() methods can be used as the template parameter for the ReferenceCountedObjectPtr… Does that help?


Wow - thats cool to know.
Yes that might just do the trick.

Another guy on a different forum in connected to REALbasic ( whose interface functionality I’m attempting to duplicate ) also responded to my plea for help
and taught me something new i didn’t know about C++ that would also fix it and that is to use the “virtual” keyword when specifying the class inheritance list as per this article.