Почему не работает полиморфизм?

Есть иерархия классов

    class Hash {
    public:
      enum SIZE {
        PASSWORDSIZE = 16,
        HASHSIZE = 32
        };
    private:
      CryptoPP::SHA256 sha256;
    protected:
      std::string hash(std::string const&, SIZE const size = PASSWORDSIZE);
      };


      class FileInterface
      {
    public:
      class UnableToWrite : public std::exception {public: virtual const char* what() const noexcept override {return "unable to write data to file";}};
      
      FileInterface() = delete;
      FileInterface(const std::string & );
      virtual ~FileInterface();
      virtual bool empty() const;
      virtual bool update(std::string const&);
    
    protected:
      std::fstream *file;
      std::string data;

      };


  struct Password {

    virtual bool empty() = 0;
    virtual bool verification(std::string const&) = 0;
    virtual bool update(std::string const&) = 0;
    virtual ~Password() = 0;

    };


        class PasswordInterface : private Hash, public FileInterface, public Password
      {
    public:
      PasswordInterface();
      ~PasswordInterface();
      bool verification(std::string const&) override;
      bool empty() const override;
    private:
      std::string hashPassword(std::string const&);
      std::string passwordFromString(std::string const&);
      };

Далее в коде есть строка Password *p = new PasswordInterface(); которая по идее должна нормально компилироваться ведь PasswordInterface это наследник класса Password но qt-creator ругается:

runcommand.cpp:6:13: Cannot initialize a variable of type 'Password *' with an rvalue of type 'PasswordInterface *'

Почему я не могу присвоить указателю на Password значение типа PasswordInterface и как это исправить?*


Ответы (1 шт):

Автор решения: AlexGlebe

Ошибка должна была быть другой : error: invalid new-expression of abstract class type 'PasswordInterface'
Потому-что класс class PasswordInterface у вас абстрактный до тех-пор, пока у него не определены виртуальные функции базового класса со знаком .. = 0 ;.

Поменяйте в struct Password декларацию виртуальной функции с добавлением константности const. Ваша константная функция не замещает не константную.

virtual bool empty() const = 0;

Добавьте реализацию функции virtual bool update(std::string const&) ;.

virtual bool update(std::string const& s){
      return FileInterface :: update(s);
}

Происходит наследование этой виртуальной функции от двух базовых классов. И решение, какую из них вызывать придётся сделать программисту явно.

→ Ссылка