I would like to initialize a member variable of a Derived class, and after that pass it to the Base class constructor. I came up with the solution below (also here: http://cpp.sh/4uu4q)
1) Does the following code have a defined or an undefined behavior (UB) ?
2) Is what I am attempting to do an indication of a bad design?
struct Data {
int fValue;
Data( int value = -1 ) : fValue( value )
{}
};
struct Base {
Base( const std::unique_ptr<Data> & derivedData ) {
std::cout << "Constructing Base derivedData=" << derivedData->fValue << std::endl;
}
};
struct Derived : public Base {
std::unique_ptr<Data> fData = std::move( fData );
Derived() : Base( ConstructData() )
{}
const std::unique_ptr<Data> & ConstructData() {
fData.release();
fData.reset( new Data(777) );
std::cout << "in ConstructData: fData->fValue =" << fData->fValue << std::endl;
return fData;
}
};
int main() {
Derived d;
std::cout << "In main: d.fData->fValue =" << d.fData->fValue << std::endl;
return 0;
}