Imagine I have a class called Test
and inside this class I have a list of pointers which their types are all from class Base
. Although any pointer which is stored in list is pointer to an object from classes which are derived from class Base
. I want to provide a getter()
function for a specific derived type which returns the object of specific class. Note that we don't know the index of required pointer inside class.
class Base
{
/// Base class do have a pure virtual function
};
class Derived1
{
};
class Derived2
{
};
Class Test
{
std::vector<Base*> pointers; /// any STL collection... vector may be more frequent
get_derived1_object(); ///
};
I think of some possible implementations of get_derived1_object()
like this (And in my opinion both have some problems):
1- storing a copy pointer of Derived1
's object's pointer inside class. In case I want to try using unique_pre
it is not a good solution.
2- iterate over pointers
in order to find which item is from Derived1
class using runtime type checking. (for example trying to use dynamic_cast
or sth similar). In my usecase, using runtime type checking is better not to be used.
P.S: having multiple items of each class is not important here because I'm sure I don't have 2 different pointers from same class inside my list and consider it taken care of.
I was wondering if I could find the best solution for providing a function like get_derived1_object
(whether from my own given solutions or sth else).