titanandrews
Programmer
Hello,
I understand with C++, I have the ability to downcast an object using dynamic_cast, although probably not something that is done too often. (Someone please correct me if I'm wrong) I created this little example here to help me understand what I can do with this operator, but I am having a problem on downcast. I get a mem-ref error because myOffice_ptr is NULL. It should be a valid cast because the bad_cast exception never gets thrown. I compiled with the option /GR to enable RTTI. (Something my book tells me to do, although I don't know what RTTI is.) Can anyone please tell me what is wrong? Any other information you want to provide on dynamic_cast is also appreciated. Thanks!
Barry
I understand with C++, I have the ability to downcast an object using dynamic_cast, although probably not something that is done too often. (Someone please correct me if I'm wrong) I created this little example here to help me understand what I can do with this operator, but I am having a problem on downcast. I get a mem-ref error because myOffice_ptr is NULL. It should be a valid cast because the bad_cast exception never gets thrown. I compiled with the option /GR to enable RTTI. (Something my book tells me to do, although I don't know what RTTI is.) Can anyone please tell me what is wrong? Any other information you want to provide on dynamic_cast is also appreciated. Thanks!
Barry
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
class Room
{
public:
virtual void cleanIt()
{
cout << "Cleaning the Room " << endl;
}
virtual Room::~Room()
{
}
};
class Office : public Room
{
public:
void cleanIt()
{
cout << "Cleaning the Office " << endl;
}
};
class Garage : public Room
{
public:
virtual void cleanIt()
{
cout << "Cleaning the Garage " << endl;
}
};
int main(int argc, char *argv[])
{
Garage *myGarage_ptr = new Garage;
myGarage_ptr->cleanIt();
//Garage to Garage. No problem.
Garage *anotherGarage_ptr = dynamic_cast<Garage *>(myGarage_ptr);
anotherGarage_ptr->cleanIt();
delete myGarage_ptr;
//Garage to Room. No problem.
Room *myRoom = dynamic_cast<Room *>(anotherGarage_ptr);
myRoom->cleanIt();
Room *anotherRoom_ptr = new Room;
anotherRoom_ptr->cleanIt();
try
{
Office *myOffice_ptr = dynamic_cast<Office *>(anotherRoom_ptr);
myOffice_ptr->cleanIt();//Failure here because myOffice_ptr is NULL.
}
catch (bad_cast &)
{
cout << "Bad cast " << endl;
}
//Illegal. Will compile with warning, but fail at runtime because Office cannot be a Garage.
//Office *myOffice = dynamic_cast<Office *>(anotherGarage_ptr);
}