Questions on OOP (Object Oriented Programming) - page 7

 
Zhunko:

Vasily, an example, please!

I only know of one case where you need to allocate memory and need a pointer to it.

I'm sure you can almost always do without it. It is desirable not to use manual memory management. There is always a standard library that has already solved these issues.


enum ENUM_CLASS_TYPE
{
   CLASS_PARENT,
   CLASS_CHILD_1,
   CLASS_CHILD_2
};

class Parent
{
   public:
      ENUM_CLASS_TYPE(void){return classType;}
      virtual string GetName(){return "Base";}
   protected:
      Parent(ENUM_CLASS_TYPE type){classType = type;}
   private:
      ENUM_CLASS_TYPE classType;
};

class Child1 : public Parent
{
   public:
      Child1() : Parent(CLASS_CHILD_1){;}
      void MethodChild1(){;}
};

class Child2 : public Parent
{
   public:
      Child2() : Parent(CLASS_CHILD_2){;}
      void MethodChild2(){;}
};

int Start()
{
   Parent* parent = new Child1();
   switch(parent.GetType())
   {
      case CLASS_CHILD_1:
      {
          Child1* ch = parent;
          ch.MethodChild2();
          break;
      }
      case CLASS_CHILD_2:
      {
          Child1* ch = parent;
          ch.MethodChild2();
          break;
      }
   }
}
 
TheXpert:
The presence of dynamic type identification usually indicates the crutch architecture of a project.


The presence of dynamic type identification indicates a high degree of polymorphism and a higher level of abstraction. It increases manageability and scalability of the project. Allows you to work with code at the interface level and encourages the programmer not to go into implementation details.
 
Vasily, I think your example is out of touch. There are templates (macros in µl), they can solve a lot of issues at compile time. And if you have to do down-conversion, you have not designed the program well (even Straustrup said that).
 
Pavlick:
Vasily, I think your example is out of touch. There are templates (macros in µl), they can solve a lot of issues at the compilation stage. And if you have to do down-conversion, you have poorly designed the program (even Straustrup said that).

What's wrong with downward gearing with strict type control? Straustrup said this when there was no type control whatsoever. Now, if you know the derived type, you can guarantee the conversion before it starts and thus avoid run-time errors.

But the advantages of down-conversion are obvious. The main one is that it works at the interface level. If the constructor of a base class is closed in the protected scope, it is an interface and abstract class and we can work with it at its level without having to know the refined implementation of its descendants. But if we implement polymorphic behavior depending on the instance type, we can surely specify the implementation of the corresponding instance and e.g. call its unique method. With virtual functions we won't even need type conversion. After all, virtual functions will call the specific implementation "behind the scenes".

 
C-4:

... With virtual functions, even a type conversion will not be required. After all, virtual functions will call a particular implementation "behind the scenes".


I have nothing against the highlighted one. You did take a different approach in the example.
C-4:

What's wrong with the falling cast when types are strictly controlled?

If you write it correctly, you simply don't need it.

P.S: I'm not lumping samapal type identification and the virtual function mechanism into the same bottle.

 

An example from a real MQL application:

Дана строка таблицы состоящая из ячеек нескольких типов. Часть из них являются обычным полями текста OBJ_TEXT, часть - кнопками OBJ_BUTTON а часть - ячейками, в которых текст можно редактировать (OBJ_EDIT). Значения введенное в ячейку типа OBJ_EDIT запоминается, и в случае его корректности формируется некий приказ, который отправляется на выполнение внешней системе. В промежутке времени между отправкой приказа и получения ответа от системы необходимо заблокировать строку таблицы таким образом, что бы все ячейки с возможностью редактирования в них текста больше не позволяли вводить в них текст. Все кнопки входящие в строку таблицы не позволяли нажимать на себя, а в целом, все ячейки в которых есть текст, должны были бы изменить его цвет на красный, сигнализируя тем самым о своей блокировке. Строки входящие в таблицу не идентичны друг другу и не содержат регулярной структуры. Одна строка может содержать кнопку, тогда как другая нет. Одна строка может содержать какой-либо столбец, а другая нет и т.д.

I would like to hear expert opinions on how they would solve such a problem. I personally solved it using dynamic type identification, "pattern method" pattern and step-down conversions. It was solved so well that it finally allowed me to create complex interactive tables with irregular, fully customizable elements. The results are so tangible that I find it naive to claim that de "dynamic identification is a crutch" and "down-conversion is evil".

p.s. Pavlick, by the way, you still haven't answered what exactly is wrong with down-conversion.

 

No, I'm far from an expert. What I said about the reduction gearing is my experience, I strive to write it that way + it is confirmed by people I respect. Writing a program to prove something is a waste of my time.

Pavlick, by the way, you still haven't answered what exactly makes downsizing bad.

It's hard to explain. I understand, but I can't say). The books will probably explain it better.

 
C-4:
enum ENUM_CLASS_TYPE
{
   CLASS_PARENT,
   CLASS_CHILD_1,
   CLASS_CHILD_2
};

class Parent
{
   public:
      ENUM_CLASS_TYPE(void){return classType;}
      virtual string GetName(){return "Base";}
   protected:
      Parent(ENUM_CLASS_TYPE type){classType = type;}
   private:
      ENUM_CLASS_TYPE classType;
};

class Child1 : public Parent
{
   public:
      Child1() : Parent(CLASS_CHILD_1){;}
      void MethodChild1(){;}
};

class Child2 : public Parent
{
   public:
      Child2() : Parent(CLASS_CHILD_2){;}
      void MethodChild2(){;}
};

int Start()
{
   Parent* parent = new Child1();
   switch(parent.GetType())
   {
      case CLASS_CHILD_1:
      {
          Child1* ch = parent;
          ch.MethodChild2(); // Это не ошибка?
          break;
      }
      case CLASS_CHILD_2:
      {
          Child1* ch = parent;// Это не ошибка?

          ch.MethodChild2();
          break;
      }
   }
}

Even if it's not an error, there are templates and typeid().
 
Pavlick:

No, I'm far from an expert.

But Stroustrup is. And so are many others. You are saying all the right things.
 
Typeid() unfortunately does not exist, and the strength of templates is static identification. Different problems are solved by different methods and to say that one method is bad and the other is good is an ahuld assumption.
Reason: