I have a class
objects and astruct
objects in C++. The struct
is responsible for populating the class
with data from a CSV file.
So the extension of this was that when I created a derived class, I also created a derived struct that would correctly fill this similar, but different derived class.
struct BaseStruct {
double var = 0;
vector<double> vectorA;
virtual BaseClass^ generateClass() {return gcnew BaseClass(this->var, this->vectorA);}
};
struct DerivedStruct : BaseStruct {
vector<double> vectorB;
virtual BaseClass^ generateClass() override {return gcnew ChildClass(this->var, this->vectorA, this->vectorB);}
};
The structs are then used by another object that does file reading, and returns the polymorphic struct to the user;
BaseStruct FileReader::GetSetupStruct(String^ parameter)
{
BaseStruct retval; //Struct to be passed back
retval = (boolLogicCondition) ? BaseStruct() : DerivedStruct(); //Should return correct type of struct
return retval;
}
However, when I attempt to use the code below, by referring to it as a base class, it automatically reverts to a base class (losing the additional vectorB
attribute) and its polymorphic nature.
I suspect it loses its derived status because a) its type in the local variable window changes when I return from the ternary operator b) setupStruct.generateClass()
only ever executes the base class method
BaseStruct setupStruct = FileReader::GetSetupStruct(parameter);//Returns struct - type should depend on parameters
Signal^ mySignal = setupStruct.generateClass(); //Should run either derived or base method
How can I use these two structs and generate the correct type at run time, but maintain the polymorphism nature without it being upcasted to the base type?