4

In C++/CLI, I want a class hierarchy similar to the following:

Foo
  FooA : Foo, ClrClassA
  FooB : Foo, ClrClassB

Is it possible for FooA to share a (non CLR) base class while also inheriting from separate CLR classes? If not, what would be the best way for FooA and FooB to share common code?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
anthony
  • 40,424
  • 5
  • 55
  • 128

2 Answers2

5

Generally speaking, composition is often better than inheritance as it tends to lead to less tightly coupled designs.

If you're mixing managed and unmanaged code, it's generally easier in my experience to wrap unmanaged code in managed code rather than visa versa.

Multiple inheritance isn't supported for managed code and there's an article on Wikipedia which explains why:

Managed C++ and the use of classes and class based objects remains prevalent like in Visual C++. The only major change to this in Managed C++ is that the capabilities of multiple inheritance are not supported. This is because of a limitation of the CLR. A class managed under the CLR's garbage collector cannot inherit more than one class

It's difficult to give a good answer as to how best to combine your classes / functionality without knowing why you want to combine the classes...

Jon Cage
  • 36,366
  • 38
  • 137
  • 215
  • 2
    To be clear, managed types do not support multiple inheritance nor do they support deriving from native types. – ildjarn Jun 06 '11 at 21:30
  • FooA will be a WinForms Control and inherit from Control, FooB will be a WPF Control and will inherit from FrameworkElement. The idea is to create a control for both WinForms and WPF that shares a fair amount of code. – anthony Jun 06 '11 at 21:30
  • @antony - Composition will certainly work for that and if you have things that need to be triggered in both types of controls from your common code you can use delegate functions: http://www.functionx.com/cppcli/classes/Lesson15c.htm – Jon Cage Jun 06 '11 at 21:34
3

You cannot have a class inherit from both a reference and native type.

Rais Alam
  • 6,970
  • 12
  • 53
  • 84
Puppy
  • 144,682
  • 38
  • 256
  • 465
  • It's even stricter: a `class` cannot inherit even one `ref class`. A `ref class` cannot inherit even one `class`. The latter is sort of a consequence of every `ref class` inheriting (possibly indirectly) from `System.Object`. – Ben Voigt Jun 06 '11 at 22:32