I ran into this problem, where I want to store different classes (sharing same interface) into a common container.
Is it posssible to do that in modern C++?
Is this allowed, when I don't want to store objects as pointers? If I have to use pointer, then what should be the recommended or cleaner way to do that?
What should be the correct approach to handle such usecases?
#include <iostream>
#include <string>
#include <vector>
enum class TYPES: int {TYPE1 = 0, TYPE2, INVALID};
class IObj
{
public:
virtual auto ObjType(void) -> TYPES = 0;
};
class InterfaceObj: IObj
{
public:
virtual auto Printable(void) -> void = 0;
};
class InterfaceTesla
{
public:
virtual auto Creatable(void) -> void = 0;
};
class CObj: InterfaceObj
{
private:
std::string msg;
public:
CObj()
{
msg = "Elon Mask!";
}
virtual auto ObjType(void) -> TYPES override
{
return TYPES::TYPE1;
}
virtual auto Printable(void) -> void override
{
std::cout<<msg<<std::endl;
}
};
class CObjTesla: public CObj, InterfaceTesla
{
private:
std::string vhc;
public:
CObjTesla()
: CObj()
{
vhc = "Cybertruck";
}
virtual auto ObjType(void) -> TYPES override
{
return TYPES::TYPE2;
}
virtual auto Creatable(void) -> void override
{
std::cout<<vhc<<" was launched by ";
Printable();
}
};
int main()
{
std::vector<CObj> vec; // How am I supposed to declare this container?
for(auto i = 0; i < 10; i++)
{
CObjTesla obj1;
CObj obj2;
vec.push_back(static_cast<CObj>(obj1)); // what should be the correct type of the container?
vec.push_back((obj2));
}
for(auto &iter : vec)
{
switch(iter.ObjType())
{
case TYPES::TYPE1:
iter.Printable();
break;
case TYPES::TYPE2:
auto temp = const_cast<CObjTesla>(iter); //?? what shoud I do here?
temp.Creatable();
break;
case TYPES::INVALID:
default:
break;
}
}
}