首页 > 解决方案 > Is there any way in C++ to cast/copy a Parent class into a Child class?

问题描述

I receive a complicated object from a framework I can't really change:

Parent parent = framework.get();

I would like to add some attributes and methods to this parent:

class Child : public Parent {
    public:
        inline Child() {}
        int extraVariable = 999;
        int extraMethod() { return 666; }
    };

Is there any way to 'cast' or copy an instantiated Parent into a Child class, other than manually copying all the attributes?

The python equivalent would be

class Child(Parent):
    def extraMethod(self):
        return 666

parent = framework.get()
parent.__class__ = Child

I realize C++ isn't python but I'm willing to hack it together (this is personal code, i.e. ugly is fine).

标签: c++inheritance

解决方案


You could add a converting constructor, or two, to Child.

Example:

class Child : public Parent {
public:
    // converting constructors
    Child(const Parent& p) : Parent(p) {}        // copy
    Child(Parent&& p) : Parent(std::move(p)) {}  // move

    //...
}

Demo


推荐阅读