CinchBlue
CinchBlue

Reputation: 6200

How can I do "opt-in" interfaces with a proxy class in C++?

I have 5 classes named A B C D E and 2 interfaces I1 I2. Using multiple inheritance, I might inherit abstract classes to implement interfaces:

class A : public I1, I2 {};


Now, I want to add more interfaces I3 I4 I5.

Having to modify all 5 class definitions is tedious and violates Don't Repeat Yourself as a programming principle.

How might I implement an interface proxy class to encapsulate the polymorphic side of the interface instead of multiple inheritance of abstract base classes?

In other words, I want to have a class be cast to an interface class without using inheritance. Would a type operator overload be suitable here? Or, perhaps using a constructor per class would be good? The goal is to minimize repetition of code.

Upvotes: 0

Views: 91

Answers (2)

bipll
bipll

Reputation: 11950

Change you classes declarations slightly to add one more level of indirection?

class A: public I;
class B: public I;
class C: public I;
struct I: I1, I2 /* we will add I3, I4 and I5 tomorrow */

Upvotes: 1

sameerkn
sameerkn

Reputation: 2259

I see this problem as follows:

  • Classes A, B, C,... are type of documents say, JPG, DOC, RTF, XML, PDF,...
  • Interfaces I1, I2, I3,... as functionalities common to documents say, IPrint, ISaveToFile, ICompress.

So, every document A, B, C,... needs to implement these inferfaces in order to provide these functionalities.

If I have described your requirement correctly then, you can use Design Pattern : Visitor.

Also, I can go in detail if this fits your requirement.

Upvotes: 1

Related Questions