Lonatico
Lonatico

Reputation: 151

Initialize child class with base class object C++?

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,

Upvotes: 4

Views: 2859

Answers (2)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

Try the decorator pattern:

struct Interface {
    virtual void function() = 0;
};
struct Implementation: Interface {
    virtual void function() { ...}
};
struct Decorator: Interface {
    explicit Decorator(Interface& decorated): m_decorated(decorated) {}
    virtual void function() {
        // Call m_decorated.function() if you want,
        // adjusting the results or parameters.
        ...
    }
private:
    Interface& m_decorated;
};

Searching for "decorator pattern" will give you a bunch of further information.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254431

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) {}
};

Upvotes: 5

Related Questions