C++ Logo


Advanced search

Re: [std-proposals] Versatility -- Classes change at runtime

From: Bo Persson <bo_at_[hidden]>
Date: Sat, 30 Jul 2022 21:19:39 +0200
On 2022-07-30 at 20:56, Frederick Virchanza Gotham via Std-Proposals wrote:
> The term 'polymorphism' when used in the context of computer programming
> is typically applied to so-called 'virtual' methods.
> Virtual methods give us more versatility when dealing with classes, and
> in particular with the classifications of classes. At runtime, a
> pointer to 'Base' can be used to interact with objects of many types
> of derived classes -- however the relationships between the base and the
> derived classes are all set in stone at compile time (that is to say: All of
> the v-tables are compile-time constants).
> I wonder if we can take classes to the next level of versatility by no
> longer requiring the v-table to be a compile-time constant? What if the
> class could change at runtime as the program progresses from one state
> to another?
> I'm going to use a really simple example. Let's say we have a base class
> called 'Mammal', with three derived classes, 'Cow', 'Sheep', 'Canine'.
> And furthermore 'Canine' has two derived classes, 'Dog' and 'Wolf'.
> Like this:
> Mammal
> |
> |
> |________ Cow
> |
> |
> |________ Sheep
> |
> |
> |________ Canine
> |
> |________ Dog
> |
> |________ Wolf
> The 'Mammal' class has a pure virtual method called 'Speak', and the
> 'Wolf' class overrides this method to print to the screen "Howl".
> Now let's say during the execution of the program, we want to change how
> Wolves work. Let's say we want them to say "Ow Ow Owwww" instead of "Howl".
> So we want to edit the v-table for 'Wolf' so that the pointer for the
> 'Speak' method points to some other method.


You *could* have a data member, and change that. Doesn't require a
language change.

Received on 2022-07-30 19:19:47