i have code like below.
Base is the base class and D1, D2, D3 are derived classes.
D1, D2 and D3 class objects can hold int, float and double values respectively.
I have a vector of base class pointers. Each one of them can point to any of the derived class objects.
Through Base class pointer i should be able to get the data present in any of the derived class.
enum Type
{
INT,
FLOAT,
DOUBLE
};
struct Data
{
Type type;
union
{
int iVal;
float fVal;
double dVal;
};
};
class Base
{
public:
virtual Data getData() = 0;
};
class D1: public Base
{
int i;
public:
virtual Data getData()
{
Data data;
data.type = INT;
data.iVal = i;
return data;
}
};
class D2: public Base
{
float f;
public:
virtual Data getData()
{
Data data;
data.type = FLOAT;
data.fVal = f;
return data;
}
};
class D3: public Base
{
double d;
public:
virtual Data getData()
{
Data data;
data.type = DOUBLE;
data.dVal = d;
return data;
}
};
getData() returns Data object.
Using the type in Data object, i need to extract corresponding value in union.
I am unable to avoid type checking even though i am using virtual function mechanism.
Is there any better way to return data through single interface function ?
EDIT: In my project scenario, at runtime it can generate few D1 objects, few D2 objects and so on. I need to pass all these objects to some other module.
So i used vector<Base *> to pass on all the objects to the next module.
Is there any better way to pass on all the objects ?
EDIT: Any Non-Boost solution exists ?
In general I’d prefer to avoid such design at all. But if you absolutely have to make it this way, the easiest and fastest method, imho, is to use boost::any.
Update: As it was, absolutely correctly, noted boost::variant may be even more convenient and efficient here, since the used types are known (thanks for the remarks).