I have a variety of objects created from template class bar (below). Each object has a data member with different data type (eg std::string, bool, int, etc.)
I have a set of current defaults of each of the derived/templated types in a static array that have been constructed via new.
I'd like to initialize the object in the constructor, WITHOUT a separate initialization step.
I can be certain that the type of default object I'm retrieving from the static array is absolutely the SAME templated type.
I figure I'm running into the problem that object bar isn't really of type object bar until the constructor finishes? Isn't there a way in C++11 to use targeted or delegate constructors to work around that?
class foo
{
public:
foo(int index) : fMyIndex(index) { }
protected:
int fMyIndex;
};
template<class T>
class bar : public foo
{
public:
// This constructor takes the integer prefIndex, then constructs
// the object based on current in-memory settings, which it obtains from a static array via static GetDefaultData;
//
bar(int index) : foo(index)
{
// get the most current version of the in-memory data. defaultObject is a pointer to a "BarString"
foo* defaultObject = static_cast<bar*>(GetDefaultData(fMyIndex));
if (defaultObject) {
// bad memory access!
*this = *defaultObject;
}
}
private:
T fMyData;
};
typedef bar<std::string> BarString;
typedef bar<int> BarInt;
typedef bar<bool> BarBool;
Of course you can use a delegated constructor, but I wonder why you get a bad memory access there:
// bad memory access!
*this = *defaultObject;
As far as I know, there is nothing wrong with that.
But indeed you can use delegated constructors, as long as you don't call the base constructor directly like you do. Instead, the copy constructor of bar
will call the appropriated constructor for its base.
template<class T>
struct bar : foo {
// This constructor takes the integer prefIndex, then constructs
// the object based on current in-memory settings, which it obtains from a static array via static GetDefaultData;
bar(int index) : bar(*static_cast<bar*>(GetDefaultData(index))) {}
private:
T fMyData;
};