Ideally, your base class(es) would provide the necessary interface that base classes override, so that you do not need to worry about the underlying type of the object: just invoke the virtual function and the respective derived class virtual function will be called.
However, sometimes it may simply be that you have a special case such that you want to check if the underlying object is of a particular derived class type, and hence do something that is not part of the base class interface. Fine, use dynamic_cast.
But this looks really bad:
Code:
for (int i = 0; i < 4; i++)
{
if (dynamic_cast <B*>(arr[i]) != nullptr)
{
cout << arr[i]->getInfo() << endl;
}
}
for (int i = 0; i < 4; i++) {
if (dynamic_cast <C*>(arr[i]) != nullptr)
{
//I want to access the current object's method and change its value, i.e setValue()
cout << arr[i]->getInfo() << endl << endl;
}
}
Why bother having an array of base class pointers in the first place? Why not have an array of B and another array of C? After all, you are not actually making use of polymorphism, so all these repeated dynamic_cast is just making your code inefficient and harder to read. Oh, and then you can freely call setValue since you will actually be dealing with a C object for sure.
If you are not using polymorphism, then the only point to inheritance is to inherit implementation, but then you should consider if it is better to extend the interface, use composition, or maybe use private inheritance.