Initialize child class with base class object C++?
c++, inheritance
Solution
You'll have to copy or move it to be part of the new object; there's no way to transform an existing object into a new type.
Initialise it in the initialiser list in the usual manner.
// Copy an existing object
InhClass(SupClass const & obj) : SupClass(obj) {}
// Move an existing object
InhClass(SupClass && obj) : SupClass(std::move(obj)) {}
To avoid copying/moving, you'd have to use something other than inheritance. You could have a "wrapper" class containing a pointer/reference to a `SupClass`, plus whatever you want to extend it with.
struct Wrapper {
SupClass & obj;
// Refer to existing object without creating a new one
Wrapper(SupClass & obj) : obj(obj) {}
};
Problem
So, the title may be a little confusing, but here is my question: I have a superclass (let's call it SupClass) and a subclass that inherits from SupClass (let's call it InhClass). Now, I want to make a constructor for my InhClass that receives a SupClass object and initializes the "SupClass part" of InhClass with it. Here is a code example trying to make it clear: ``` Class SupClass { public: SupClass() { //Initialize SupClass object } }; Class InhClass : private SupClass { public: InhClass(SupClass obj) { //Initialize SupClass inheritance with obj } }; ``` This would be to use in a case where you already have a SupClass object initialized (and possibly worked on) but for a short period, or from then on you want to use a InhClass object. Instead of copying everything (or closing and reopening a file, for example), I would be able to just initialize my child class with its base class object. Thanks in advance, I'm sorry about any english mistakes,