Question

I'm trying to figure out a way to call a superclass constructor after processing some info. I have something like Foo and FooSubclass, and want to do something like this.

class Foo{
    Info info;
    Foo::Foo(Info input){info = input};
}

class FooSubclass : public Foo{
    Info info;
    FooSubclass::FooSubclass(Info input){
        Info moreInput = unpackInput(input);
        Foo(moreInput);
    }
}

so that I unpack some information in the constructor before passing it off to the superclass constructor. I think this isn't currently allowed in C++11 - is there another way to do this?

Thanks.

Was it helpful?

Solution

Assuming you can copy Info you may "unpack" it the object in an function and return an Info object directly to the constructor of the base class:

class FooSubclass
    : public Foo // it seems you mean to this as base class
{
    static Info unpackInput(Info input);
public:
    FooSubclass(Info input):
        Foo(unpackInput(input))
    {
    }
};

If you actually need to store an object, e.g., because copying/moving the object isn't feasible for whatever reason (even the copy/move may be elided), you can play a trick with virtual base classes (which doesn't come entirely free, though):

struct PrivateBase
{
    Info unpackedInput;
    PrivateBase(Info input)
        unpackedInput(input) {
        // do whatever else needs to be done to unpack the input
    }
};
class FooSubclass
    : private virtual PrivateBase, public Foo
{
public:
    FooSubclass(Info input)
        : PrivateBase(input) // this one is guaranteed to be constructed first!
        , Foo(unpackedInput)
    {
    }
};

When multiply inheriting base classes, the construction order of the bases is in the order they are declared. In case there are virtual base classes involved, these are constructed before all normal base classes. In the above example, the base class PrivateBase is simply inherited first to guard against a virtual base being in the Foo hierarchy. Ifi that isn't the case, normal inheritance can be used.

Anyway, since the base class constructors are execute first, they can be [ab?]used to do the additional computations you want to inject and set up any necessary value. These can then be passed to the base class by reference is needed.

OTHER TIPS

Base class cTors are always executed first. After that the derived class cTor will run to give you final Derived class object.

Maybe you can try to do the processing outside, before the objects are created and then pass the info the base class.

To keep things very very simple do this outside all the cTors (Base and Derived)

Info moreInput = unpackInput(input);    

Then pass the moreInput to the Base class, via the derived class cTor initializer list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top