I am trying to use dynamic_cast - with no success. I have a BASE class, and a class A derived from BASE. I want to have a pointer to a BASE class object which I later want to cast to class A. I clearly am not doing this correctly. The following code compiles:
#include <cstdio>
class BASE {
private:
int i;
public:
BASE(void) {i = 1; }
virtual ~BASE(){}
virtual void id() { printf("CLASS BASE\n"); }
};
class A : public BASE {
public:
A(void): BASE() {}
A(const BASE & base) : BASE(base) {}
A& operator = (const BASE & base) { static_cast<BASE&>(*this) = base; return *this; }
void id() override { printf("CLASS A\n"); };
};
int main() {
BASE* base = new BASE();
base->id();
A* a = new A(*base);
a->id();
A* anotherA = dynamic_cast<A*>(base);
if(!anotherA)
printf("anotherA is NULL\n");
else
anotherA->id();
}
but running it gives:
CLASS BASE
CLASS A
anotherA is NULL
I am sure I'm missing something very basic, but I keep staring at the code and can't see what I'm doing wrong. Any help would be very much appreciated.
I have looked at
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
but don't understand why dynamic_cast doesn't work - isn't this just a simple downcast?