Why C ++ does not allow to request a pointer to the most derived class?

(This question should probably be answered with reference to Stroustrup.)

It seems extremely useful to be able to query for a pointer to the most derived class, as shown below:

class Base { ... };
class DerivedA { ... };
class DerivedB { ... };
class Processor
{
  public:
  void Do(Base* b) {...}
  void Do(DerivedA* d) {...}
  void Do(DerivedB* d) {...}
};

list<Base*> things;
Processor p;
for(list<Base*>::iterator i=things.begin(), e=things.end(); i!=e; ++i)
{
    p.Do(CAST_TO_MOST_DERIVED_CLASS(*i));
}

But this mechanism is not provided in C ++. Why?

Update motivating example:

Suppose instead of a base and a derivative and a processor you have:

class Fruit
class Apple : public Fruit
class Orange: public Fruit

class Eater
{
   void Eat(Fruit* f)  { ... }
   void Eat(Apple* f)  { Wash(f); ... }
   void Eat(Orange* f) { Peel(f); ... }
};

Eater me;
for each Fruit* f in Fruits
    me.Eat(f);

But this is difficult to do in C ++, requiring creative solutions such as a visitor template. So the question is: why is it difficult to do in C ++ when something like "CAST_TO_MOST_DERIVED" makes it so much easier?

Update: Wikipedia knows everything

I think Pont Gagge has a good answer. Add to this this bit from the Wikipedia entry Multiple Dispatch :

" , - " ++ " ++, , ( ) . , , , , , C/++ , ".

Multi-Methods, , , , , .

+5
10

, , switch , . , , : , .

, - , Processors. ?

-, , " " . , , ? ? - ++ !

-, , , ( ++ , ). , , ? , Processor ? , ? ? , ?

, , , , , .

+4

, , , . , , .

+8

-, ++ (.. ). , dynamic_cast void*.

-, . ++ , - . . , . ++.

, ( ), , . , .

+8

. , . ++ , .

+6

. * DerivedA/B. .

, .

, .

+4

++ . *i . , ++ , . ( ), dynamic_cast , .., . - DerivedB , , .

+2

. ++, , , , . , .

+2

++, , , :

class Base
{
    virtual void accept(BaseVisitor& visitor) { visitor.visit(this); }
};

class DerivedA
{
    virtual void accept(BaseVisitor& visitor) { visitor.visit(this); }
};

class DerivedB
{
    virtual void accept(BaseVisitor& visitor) { visitor.visit(this); }
};

class BaseVisitor
{   
    virtual void visit(Base* b) = 0;
    virtual void visit(DerivedA* d) = 0;
    virtual void visit(DerivedB* d) = 0;
};

class Processor : public BaseVisitor
{
    virtual void visit(Base* b) { ... }
    virtual void visit(DerivedA* d) { ... }
    virtual void visit(DerivedB* d) { ... }
};

list<Base*> things;
Processor p;
for(list<Base*>::iterator i=things.begin(), e=things.end(); i!=e; ++i)
{
    (*i)->visit(p);
}
+1

++ ? , . , , . , , .

, :

, , , , . , class DerivedC : Base {...};. , Processor::Do .

, , ? . , , ? ? ? ? - , , ?

, , , , .

+1

++ . DerivedA * DerivedB * , Base *. , , , . LESS, , , , , .

0

All Articles