pointers - C++ types of casting, what they're doing, and which variables are valid? -
this question has answer here:
ok i'm having trouble understanding different types of casting , whats going on them. created 2 classes: , b. b derived a.
i made bunch of pointers , dumb them screen. need understanding what's going on , variables valid.
here's code:
#include <iostream> using namespace std; class { public: a(int ivalue){ m_ivalue = ivalue; } a(){ m_ivalue = 10; } virtual void dosomething(){ cout << "the value " << getvalue() << endl; } void dosomethingelse(){ cout << "this else" << endl; } virtual int getvalue(){ return m_ivalue; } private: int m_ivalue; }; class b : public a{ public: b() : a(5){ } virtual void dosomething(){ cout << "this time, value " << getvalue() << endl; } void dosomethingelse(){ cout << "this else entirely" << endl; } virtual void doanotherthing(){ cout << "and third thing" << endl; } }; int main(int argc, char * argv[]){ * pa1 = new b; * pa2 = new a; b * pb1; b * pb2; pb1 = (b*)pa1; pb2 = (b*)pa2; cout << "step 1 - c style cast:" << endl; cout << " pa1 cast pointer pb1: " << pb1 << endl; cout << " pa2 cast pointer pb2: " << pb2 << endl << endl; b * pb3; b * pb4; pb3 = dynamic_cast<b*>(pa1); pb4 = dynamic_cast<b*>(pa2); cout << "step 2 - dynamic_cast:" << endl; cout << " pa1 cast pointer pb3: " << pb3 << endl; cout << " pa2 cast pointer pb4: " << pb4 << endl << endl; b * pb5; b * pb6; pb5 = static_cast<b*>(pa1); pb6 = static_cast<b*>(pa2); cout << "step 3 - static_cast:" << endl; cout << " pa1 cast pointer pb5: " << pb5 << endl; cout << " pa2 cast pointer pb6: " << pb6 << endl << endl; b * pb7; b * pb8; pb7 = reinterpret_cast<b*>(pa1); pb8 = reinterpret_cast<b*>(pa2); cout << "step 4 - reinterpret_cast:" << endl; cout << " pa1 cast pointer pb7: " << pb7 << endl; cout << " pa2 cast pointer pb8: " << pb8 << endl << endl; return 0; }
here's outputs:
step 1 - c style cast: pa1 cast pointer pb1: 0x1853010 pa2 cast pointer pb2: 0x1853030 step 2 - dynamic_cast: pa1 cast pointer pb3: 0x1853010 pa2 cast pointer pb4: 0 step 3 - static_cast: pa1 cast pointer pb5: 0x1853010 pa2 cast pointer pb6: 0x1853030 step 4 - reinterpret_cast: pa1 cast pointer pb7: 0x1853010 pa2 cast pointer pb8: 0x1853030
Comments
Post a Comment