Beginning Architectural Theme of C ++ Inheritance

Based on pure “C”, I start from scratch and more or less new to OO-Development, so I apologize in advance for my “naive” view on the topic below. Later I tried to describe my problem in an abstract style (my real classes are different). Parts of the code may be incompatible and should only be considered as “thoughts”.

I have several classes inheriting from the base class:

    class Base
    {

    };


    class Derived1 : Base
    {

    };

    class Derived2 : Base
    {

    };

    class Derived3 : Base
    {

    };

In addition, the vector contains pointers to instances of derived classes:

    std::vector<Base *> collection;

, . : , / ? - , , .

dynamic_cast (...) ? ...

"", , :

, :

    class Derived1;
    class Derived2;
    class Derived3;

    class AbstractUserOperation
    {
        virtual void call(Derived1 * cl) = 0;
        virtual void call(Derived2 * cl) = 0;
        virtual void call(Derived3 * cl) = 0;
    };

, :

    class ConcreteUserOperation : AbstractUserOperation
    {
        virtual void call(Derived1 * cl)
        {
            ...
        }

        virtual void call(Derived2 * cl)
        {
            ...
        }

        virtual void call(Derived3 * cl)
        {
            ...
        }

    };

, , "":

    class Base
    {
        virtual void evaluate(AbstractUserOperation* o) = 0;

    };


    class Derived1 : public Base
    {
        void evaluate(AbstractUserOperation *o)
        {
            o->call(this);
        }

    };

    class Derived2 : public Base
    {
        void evaluate(AbstractUserOperation *o)
        {
            o->call(this);
        }

    };

    class Derived3 : public Base
    {
        void evaluate(AbstractUserOperation *o)
        {
            o->call(this);
        }
    };

:

    std::vector<Base *> collection;

    ConcreteUserOperation o; // a user defined class, doing whatever with x

    x = collection[i];

    x->evaluate(&o); // call user defined operation o on x

, - "", , , , , .

??? , : -)

,

+4
1

, , . , ConcreteUserOperation, Derived - std:: function . . Samplecode:

  #include <functional>

  struct Base {};

  struct Derived : public Base
  {
     void evaluate(std::function<void(const Derived&)> callback) const
     {
        callback(*this);
     }

     int foo = 42;
  };

  int main()
  {
     Derived d;
     d.evaluate([](const Derived& d){std::cout << d.foo << std::endl;});
  } 

: http://coliru.stacked-crooked.com/a/223af4a43077a760

0

Source: https://habr.com/ru/post/1531051/


All Articles