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

后端 未结 16 1799
忘掉有多难
忘掉有多难 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 06:52

    No it's not possible to change the type of an object once instantiated.

    *object = baseObject; doesn't change the type of object, it merely calls a compiler-generated assignment operator.

    It would have been a different matter if you had written

    object = new Base;

    (remembering to call delete naturally; currently your code leaks an object).

    C++11 onwards gives you the ability to move the resources from one object to another; see

    http://en.cppreference.com/w/cpp/utility/move

提交回复
热议问题