jeudi 7 mars 2019

How to use strategy pattern with additional methods in derived classes

I'm writing a project in which I'm using strategy, however, my derived classes have other additional functionalities which the base class shouldn't have.

class Base {
        public:
            virtual void execute() = 0;
            virtual void print() const noexcept = 0;
            virtual ~Base() {}
        };


class DerivedA : public virtual Base {
        public:
            void execute() override;
            void print() const noexcept override;
            void doSomething();

        private:
            int x;
            double y;
};

class DerivedB final : public Base {
        public:
            void execute() override;
            void print() const noexcept override;
            std::string getZ() const noexcept;

        private:
            std::string z;
        };


In main(), I'm trying to use dynamic_cast to be able to use this additional functionality like this:

int main() {

    DerivedA da;
    Base* base = &da;
    DerivedA* derivedA = dynamic_cast<DerivedA*>(base);
    derivedA.doSomething();

    return 0;
}


But when I try to run the code I get the following error:

'DerivedA *' differs in levels of indirection from 'DerivedA'


My questions are, should I be even using strategy for this, or should I be using another design pattern? And if I should use strategy, how can I solve this error?

Aucun commentaire:

Enregistrer un commentaire