I asked a question earlier but it turns out my problem was not properly modeled by my example. So here is my actual problem:
A
, and c
Others have already explained how it can be achieved.
I'll just limit myself to why it is so.
B gets implicitly cast to A here. So it currently has only properties of A.
The upward casting is implicit in C++.
Downcasting in C++ is possible only if your base class is polymorphic.
In short polymorphic requirement is nothing but something in your base class that can be overridden by your derived!! Virtual methods
then you can use RTTI and dynamic_cast as prescribed by others to do that.
Example:
#include
#include
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 l;
l.push_back(new B());
l.push_back(new B());
//Prints A
for (std::list::iterator it = l.begin(); it != l.end(); ++it)
bar(**it);
//Prints B
for (std::list::iterator it = l.begin(); it != l.end(); ++it)
bar(dynamic_cast(**it));
}
Answer:
This is an A
This is an A
This is a B
This is a B
Note: This is only if your list has objects of type B. Otherwise, its going to crash out. This only explains upcast vs downcast