mardi 7 mars 2023

virtual method overridden issue with unique_ptr move semantics [duplicate]

It looks like in below code snippet virtual method overridden is not happening with Adapter object and both Target and Adapter object is showing same output.

    #include <iostream>
    #include <memory>
    
    using namespace std;
    
    class Target
    {
       public:
        virtual std::string getResponse ()   
      {
              return "simple response";
       }
   };
    
    class Adaptee
    {
     public:
       std::string getSpecialRequest ()   
      {
              return "Special response";
       }
    };
    
    class Adapter:public Target
    {
       unique_ptr < Adaptee >  m_adaptee;
     public:
        Adapter (unique_ptr < Adaptee >  adaptee )  :  m_adaptee (std::move (adaptee))   
      {
          // m_adaptee = std::move (adaptee);
       }
         std::string getResponse ()  const 
      {
           return m_adaptee->getSpecialRequest ();
       }
     };
    
    class client
    {
                        
          unique_ptr < Target >  m_target;
        public:
          client ( unique_ptr < Target > target)    
      {
                m_target = std::move (target);
           std::cout << m_target->getResponse ();
        }
     };
    
    int main ()
    {
          
          unique_ptr <Target> oj =  make_unique <Target> ();
          unique_ptr <Adaptee > oj1  =  make_unique <Adaptee> ();
          unique_ptr < Target > oj2  = make_unique<Adapter> (std::move(oj1));
          client instance (std::move (oj));
          client oj3 (std::move (oj2));
          return 0;
    }

output : simple response simple response

expected output : simple response special response;

it looks like it is issue of object transfer-ship from Target to Adapter object.Please suggest.

Aucun commentaire:

Enregistrer un commentaire