简体   繁体   中英

Constructor initializer list doesn't follow order

I have following code:

class Base
{
public:
    Base(int test) { std::cout << "Base constructor, test: " << test << std::endl; }
};

class Derived : public Base
{
private:
    int variable;

public:
    Derived() :
        variable(50),
        Base(variable)
    {}
};

Derived derived;

And I would expect that output would be: "Base constructor, test: 50", but that isn't the case, because Base constructor gets called before variable is initialized, there is no error nor warning, it just compiles.

Is there any way i can make Base constructor get called after? Or is this generally bad design?

I'm tryting to get rid of all the init methods and their calls by putting them into constructor insted, this behavior stop me from doing that.

Is there any way i can make Base constructor get called after?

No. An object's constructor must construct its base classes before any named member variables.

I'm trying to get rid of all the init methods and their calls by putting them into constructor instead

That is a worthwhile effort!

I'll assume your real code variable is something more complex than an int . Because if it's an int, you could simply call Base(50) .

You can use delagating constructors to prepare a variable before any constructor begins initialization.

class Derived : public Base
{
public:
    // Generate an important value FIRST, and then delegate
    // construction to a new constructor.
    Derived() : Derived( GenerateSomethingComplex() ) {}

private:

    // Here, we can honor constructing Base before Derived
    // while "some value" has been procured in advance.
    Derived( SomethingComplex&& var) :
        Base( var ),
        variable( std::move(var) )
    {}

    SomethingComplex variable;

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM