What if constructors could...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class AbstractBase
{
    //...
public:
    //...
    AbstractBase(istream &deserialize_from) mutable
    {
        unsigned ObjType = 0;
        deserialize_from >> ObjType;
        switch(ObjType)
        {
        case 1:
            SomeDerivedClass::SomeDerivedClass(this, deserialize_from);
        case 2:
            AnotherDerived::AnotherDerived(this, deserialize_from); //may handle its own derived classes
        //...
        }
    }
    virtual void Serialize(ofstream &to) const
    {
        to << data;
        //expect extending classes to have called this first...
    }
    //...
};
1
2
3
//...
AbstractBase *p = new AbstractBase(infile); //magically constructs correct instance
//... 
Imagine a standard of C++ where static factories are a thing of the past...


Just interesting to think about.
1. Do you think eliminating the need for static factories with some sort of new constructor syntax would be a good idea?
2. If yes, how do you think the syntax should/would have to be?
3. If you think this is a horrible idea and/or that I am mentally insane, why do you think static factories are better/easier?

Personally I think static factories make plenty of sense and are perfectly fine as they are, but I was just curious to consider a different way of doing things.
Last edited on
I don't see how this is different from a factory. The only thing that's changed is you moved the factory code from a dedicated function and dropped it in the parent class ctor. I don't see any advantage to doing that.
Google around C++11 rvalue references and perfect forwarding for a new take on the factory pattern.
Topic archived. No new replies allowed.