463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

How can I make a class implement an interface .... (C++)

... when the class acutally does provide implementations for all abstract methods, but is not "formally" implementing the interface?

Lets say I have the following:

class AInterface {
    public:
        virtual void mem_func()=0;
        virtual ~AInterface(){}
};

void AFunction(AInterface* i){};

class BClass {
    public:
        void mem_func(){}
        virtual ~BClass(){}
};

and I cannot change any of this but I want to use an object of class BClass to call AFunction.

Actually, I would like to write something like

class MyABClass : public BClass,public AInterface {};

but this doesnt help (the class just inherits both methods and is abstract). I guess one way to do this is writing something like

class MyABClass : public AInterface {
    public:
        void mem_func(){a.mem_func();}
    private:
        BClass a;
}

This works fine, but I wonder if it is possible to save some writing or if there is some better way to deal with this situation.

Upvotes: 2

Views: 146

Answers (2)

TobiMcNamobi
TobiMcNamobi

Reputation: 4813

I would use an approach quite similar to your last code snippet

class MyABClass : public AInterface {
    public:
        void MyABClass(BClass &_a)
            : a(_a)
        {}
        void mem_func(){a.mem_func();}
    private:
        BClass &a;
}

This is a design pattern and is called Adapter (with delegation). Maybe you also want to read about the Proxy pattern.

Update (considering Kenny's comment): Whether you pass BClass as a reference or a copy is debatable. It depends on what you want. If you want a wrapper for conveniently altering the original BClass instance then use BClass & as constructor parameter. On the other hand if a copy is sufficient then use just BClass without ampersand &. Well, if a copy constructor is available. Finally you have to pay attention when using a reference that you may create side-effects (which, again, may be desired or not).

Upvotes: 2

Kenny Ostrom
Kenny Ostrom

Reputation: 5871

Your first attempt was almost right

class MyClass : public AClass,public AInterface {};

The problem is that MyClass does not know that AClass::A() satisfies the requirement posed by AInterface::A()=0. Give it a little help like so

class MyClass : public AClass, public AInterface {
    void A() {AClass::A();}
};

Upvotes: 0

Related Questions