Others have already explained how this can be achieved.
I will simply limit myself to why this is so.
B is implicitly given in here. Thus, currently it has only properties A.
Upstream casting is implied in C ++.
Downcasting in C ++ is only possible if your base class is polymorphic.
In short, a polymorphic requirement is nothing more than something in your base class that can be overridden by your derivative !! Virtual methods
then you can use RTTI and dynamic_cast, as prescribed by others, to do this.
Example:
#include <iostream> #include <list> class A { public: virtual void dummy() = 0; }; class B : public A { public: void dummy() { } }; void bar(A &a) { std::cout << "This is an A" << std::endl; } void bar(B &b) { std::cout << "This is a B" << std::endl; } int main(int argc, char **argv) { std::list<A *> l; l.push_back(new B()); l.push_back(new B()); //Prints A for (std::list<A *>::iterator it = l.begin(); it != l.end(); ++it) bar(**it); //Prints B for (std::list<A *>::iterator it = l.begin(); it != l.end(); ++it) bar(dynamic_cast<B&>(**it)); } Answer: This is an A This is an A This is a B This is a B
Note. This is only if there are objects of type B in your list. Otherwise, it will fail. This only explains that upcast vs downcast
source share