Just a quick question regarding class hierarchy movement... I've googled and looked a tutorials, but just thought a human point-of-view would be more reliable as my exact answer I did not find.
I'm trying to figure out why the following doesn't work.. the dynamic_cast I would think should work, but it complains that the pointer being dynamically cast isn't a polymorphic type. I would think since dynamic_cast is a run-time thing it would recognize that I'm trying to cast from class C up to class B. Anyways my ultimate questions are:
1 - If the pointer is to a base class can I safely use new to have it create a derived class.2 - If I were to replace the dynamic_cast in the following code with a non-checked cast is it valid?Code:A *test = new C; // <--- This valid? I assume it isCode:A *test = new C; B *foo = (B*)(test);Code:class A{ public: void set(int z){a = z;}; int a; }; class B : public A{ public: int c; void hello(){}; void set(int z){b = z;}; int b; }; class C : public B{ public: void set(int z){c = z;}; int c; }; int main() { A *test = new C; B *foo = dynamic_cast<B*>(test); // I understand why it fails because the pointer is technically of class A, but is this safe? foo->set(1); delete test; return 0; }



LinkBack URL
About LinkBacks



CornedBee