Is it possible to change a C++ object's class after instantiation?

后端 未结 16 2149
忘掉有多难
忘掉有多难 2021-02-02 06:50

I have a bunch of classes which all inherit the same attributes from a common base class. The base class implements some virtual functions that work in general cases, whilst eac

16条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 07:07

    You can at the cost of breaking good practices and maintaining unsafe code. Other answers will provide you with nasty tricks to achieve this.

    I dont like answers that just says "you should not do that", but I would like to suggest there probably is a better way to achieve the result you seek for.

    The strategy pattern as suggested in a comment by @manni66 is a good one.

    You should also think about data oriented design, since a class hierarchy does not look like a wise choice in your case.

提交回复
热议问题