polymorphism - Adapter pattern in C++, with non-virtual adapted methods -


i want create adapter class in c++, interface want adapt has several non-virtual methods. can still use regular adapter pattern?

    #include <iostream>     using namespace std;      class  newinterface{     public:       int methoda(){ cout << "a\n"; }       virtual int methodb(){ cout << "b\n"; }     };      class oldinterface{     public:       int methodc(){ cout << "c\n"; }       int methodd(){ cout << "d\n"; }     };      class old2newadapter: public newinterface {     public:       old2newadapter( oldinterface* ){ adaptee = a; }       int methoda(){ return adaptee->methodc(); }       int methodb(){ return adaptee->methodd(); }     private:       oldinterface* adaptee;     };      int main( int argc, char** argv )     {       newinterface* ni = new old2newadapter( new oldinterface() );       ni->methoda();       ni->methodb();       return 0;     } 

if have setup, output "a d" instead of "c d" should.

so how can adapt oldinterface newinterface, without rewriting newinterface methods virtual?

can introduce class? if can can replace functions use newinterface newerinterface:

class newerinterface { public:     int methoda()     {         // preconditions         int const result = domethoda();         // postconditions         return result;     }      int methodb()     {         // preconditions         int const result = domethodb();         // postconditions         return result;     }  private:     virtual int domethoda() = 0;     virtual int domethodb() = 0; };  class old2newerinterface : public newerinterface { public:     explicit old2newerinterface(oldinterface& x) : old_(&x)  private:     virtual int domethoda() { return old_->methodc(); }     virtual int domethodb() { return old_->methodd(); }  private:     oldinterface* old_; };  class new2newerinterface : public newerinterface { public:     explicit new2newerinterface(newinterface& x) : new_(&x)  private:     virtual int domethoda() { return new_->methoda(); }     virtual int domethodb() { return new_->methodb(); }  private:     newinterface* new_; }; 

Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -