Home > Software design >  Interfaces in cpp
Interfaces in cpp

Time:01-25

As you will soon see, I am not a c developer and for this problem I am working on c is my only option. I don't mind learning, so just some guidance would be appreciated.

I have a panel class as follows:

class Panel {
    ...  // Methods that implement Panel
    virtual void draw() = 0;
    ...  // Other methods to implement Panel
}

And I want two varieties of it so I create two interfaces

class Foo {
    virtual void foo() = 0;
}

class Bar: public Foo {
    virtual void bar() = 0;
}

I want to pass the implementing class of Foo to other classes and have them only be able to call the method foo, and the same for Bar.

In other languages I could create the class that implements Foo as:

class FooPanel : public Panel,  implements Foo{ ... }

or

class BarPanel : public Panel, implments Bar { ... }

then I can pass into a method:

//method(..., foo* pFoo, ...);  the signature
  method(..., (Foo*)&barPanel, ...);

The only way I can see to accomplish this in c is to:

class FooPanel : public Panel {
    virtual void foo() = 0;
}

then one has to pass the entire Panel and the implementer is capable of calling and Panel method.

Where can I look to get an idea of how this can be done?

CodePudding user response:

What other languages (such as java) call "interfaces" is just an abstract base class in C . So if you just replace the implements keyword with public virtual, it will work as you expect:

class FooPanel : public Panel, public virtual Foo { ... }

class BarPanel : public Panel, public virtual Bar { ... }
  •  Tags:  
  • Related